target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
openbabel-2.4.1/doc/API/html/search/variables_11.js | sxhexe/reaction-route-search | var searchData=
[
['rab0',['rab0',['../classOpenBabel_1_1OBFFConstraint.shtml#aa1e6a4fbe89b7309e09a9ecd6b410f11',1,'OpenBabel::OBFFConstraint']]],
['ratedata',['RateData',['../namespaceOpenBabel.shtml#a94007d911a76e1404494fd9b1785f22b',1,'OpenBabel']]],
['rates',['Rates',['../classOpenBabel_1_1OBRateData.shtml#ab82756a04d7c0ab192a0251dc888d748',1,'OpenBabel::OBRateData']]],
['rbc0',['rbc0',['../classOpenBabel_1_1OBFFConstraint.shtml#a30de1b49893da89052152acbac377988',1,'OpenBabel::OBFFConstraint']]],
['reactiontype',['ReactionType',['../classOpenBabel_1_1OBRateData.shtml#a2408b8dee598f5d056e4852f61f3a7fc',1,'OpenBabel::OBRateData']]],
['readytoinput',['ReadyToInput',['../classOpenBabel_1_1OBConversion.shtml#a9bdd5c815677e240cec9c2e4a71d73f2',1,'OpenBabel::OBConversion']]],
['recur',['recur',['../unionOpenBabel_1_1__AtomExpr.shtml#af94d20e7c35dc6021db672bddc719e59',1,'OpenBabel::_AtomExpr::recur()'],['../unionOpenBabel_1_1__AtomExpr.shtml#a402506eb5f889d2537f62f375225cf96',1,'OpenBabel::_AtomExpr::recur()']]],
['red',['red',['../structOpenBabel_1_1OBColor.shtml#a8e15743f85d7d7df6996ddfcf089df8f',1,'OpenBabel::OBColor::red()'],['../namespaceOpenBabel.shtml#a8759fc55507d155f4eb9fa303cfecc59',1,'OpenBabel::red()']]],
['refs',['refs',['../structOpenBabel_1_1OBTetrahedralConfig.shtml#a3e3f2a8fefc9f694040bbb8685cb61e1',1,'OpenBabel::OBTetrahedralConfig::refs()'],['../structOpenBabel_1_1OBCisTransConfig.shtml#a3e3f2a8fefc9f694040bbb8685cb61e1',1,'OpenBabel::OBCisTransConfig::refs()'],['../structOpenBabel_1_1OBSquarePlanarConfig.shtml#a3e3f2a8fefc9f694040bbb8685cb61e1',1,'OpenBabel::OBSquarePlanarConfig::refs()'],['../structOpenBabel_1_1OBCisTransStereo_1_1Config.shtml#a3e3f2a8fefc9f694040bbb8685cb61e1',1,'OpenBabel::OBCisTransStereo::Config::refs()'],['../structOpenBabel_1_1OBSquarePlanarStereo_1_1Config.shtml#a3e3f2a8fefc9f694040bbb8685cb61e1',1,'OpenBabel::OBSquarePlanarStereo::Config::refs()'],['../structOpenBabel_1_1OBTetrahedralStereo_1_1Config.shtml#a3e3f2a8fefc9f694040bbb8685cb61e1',1,'OpenBabel::OBTetrahedralStereo::Config::refs()']]],
['resdat',['resdat',['../namespaceOpenBabel.shtml#a30154f62f3bd1a1b8613a080444e69d7',1,'OpenBabel']]],
['residue',['Residue',['../namespaceOpenBabel.shtml#a1c64f54dc7b18535a4e9cc581199e26a',1,'OpenBabel']]],
['resno',['ResNo',['../namespaceOpenBabel.shtml#af4a6dc069703276b9476ce6b7c5f018e',1,'OpenBabel']]],
['result',['result',['../structOpenBabel_1_1detail_1_1max__value.shtml#ac7d461ddec7ac180a645b11e023314a8',1,'OpenBabel::detail::max_value::result()'],['../structOpenBabel_1_1detail_1_1max__value_3_01T_00_010_01_4.shtml#ac7d461ddec7ac180a645b11e023314a8',1,'OpenBabel::detail::max_value< T, 0 >::result()']]],
['rgt',['rgt',['../unionOpenBabel_1_1__AtomExpr.shtml#a3ac29da5e05a062a121b17962c0962a4',1,'OpenBabel::_AtomExpr::rgt()'],['../unionOpenBabel_1_1__BondExpr.shtml#a92d143f4a18107be5ba1889660041341',1,'OpenBabel::_BondExpr::rgt()']]],
['ring_5fid',['ring_id',['../classOpenBabel_1_1OBRing.shtml#ab121c8e013115dd3efb26601ad1975d0',1,'OpenBabel::OBRing']]],
['ringtyper',['ringtyper',['../namespaceOpenBabel.shtml#ae5fd3b39a867e164de9f433a78d9d09f',1,'OpenBabel']]],
['rinlen',['rInlen',['../classOpenBabel_1_1OBConversion.shtml#a1a897c3f35235e4ca7da37ca245db065',1,'OpenBabel::OBConversion']]],
['rinpos',['rInpos',['../classOpenBabel_1_1OBConversion.shtml#a545a1341008a23c2dd0721c164a9ad89',1,'OpenBabel::OBConversion']]],
['roots',['Roots',['../namespaceOpenBabel.shtml#a19c1a2a80cf2af5131ca597d0ce38192',1,'OpenBabel']]],
['rotconsts',['RotConsts',['../classOpenBabel_1_1OBRotationData.shtml#a158f9d92716703712f00b3b041adc3cc',1,'OpenBabel::OBRotationData']]],
['rscache',['RSCACHE',['../classOpenBabel_1_1OBSmartsMatcher.shtml#a0941360bb72df02227939bd307707c25',1,'OpenBabel::OBSmartsMatcher']]],
['rydberg_5fto_5fkcalpermol',['RYDBERG_TO_KCALPERMOL',['../namespaceOpenBabel.shtml#a6f1f2a4bf3acd168b5b6b8907615141f',1,'OpenBabel']]]
];
|
src/views/new_post/component.js | kadira-samples/rethinking-redux-demo | import React from 'react';
import { Link } from 'react-router';
class NewPost extends React.Component {
render() {
const {postAdding} = this.props;
return (
<div>
<h3>Add a New Post</h3>
{postAdding? "Adding..." : this.renderButton() }
</div>
);
}
renderButton() {
const {addPost} = this.props;
return (
<button onClick={addPost}>AddNow</button>
);
}
}
export default NewPost;
|
src/components/search_bar.js | theoryNine/react-video-browser | import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
}
render() {
return (
<div className="search-bar">
<input
value={this.state.term}
onChange={(event) => this.onInputChange(event.target.value)} />
</div>
);
}
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term);
}
}
export default SearchBar; |
client/src/components/Utils/Popup.js | nrandecker/nightlife | import React from 'react';
import PropTypes from 'prop-types';
import 'url-search-params-polyfill';
class Popup extends React.Component {
componentDidMount() {
this.openPopup();
}
openPopup() {
const { popupUrl, redirectUri, auth, handlePopup } = this.props;
const width = 500;
const height = 500;
const options = {
width,
height,
top: window.screenY + ((window.outerHeight - height) / 2.5),
left: window.screenX + ((window.outerWidth - width) / 2),
};
const win = window.open(
popupUrl, '_blank',
`height=${options.height},
width=${options.width},
top=${options.top},
left=${options.left}`,
);
if (win) win.focus();
const pollTimer = window.setInterval(() => {
try {
if (!!win && win.location.href.indexOf(redirectUri) !== -1) {
const params = new URLSearchParams(win.location.search);
const token = params.get('token');
win.clearInterval(pollTimer);
win.close();
auth(token);
}
} catch (e) {
// Ignore DOMException: Blocked a frame with origin from accessing a cross-origin frame.
// A hack to get around same-origin security policy errors in Internet Explorer.
}
}, 100);
// close popup
handlePopup();
}
render() {
return null;
}
}
Popup.propTypes = {
popupUrl: PropTypes.string.isRequired,
redirectUri: PropTypes.string.isRequired,
auth: PropTypes.func.isRequired,
handlePopup: PropTypes.func.isRequired,
};
export default Popup;
|
js/setup.js | weihanglo/pycontw-mobile | import React from 'react'
import {Platform} from 'react-native'
import {Provider} from 'react-redux'
import {createStore, applyMiddleware} from 'redux'
import {composeWithDevTools} from 'remote-redux-devtools'
import thunk from 'redux-thunk'
import reducer from './reducers'
import App from './App'
// Redux Store Configuration
const middlewares = [thunk]
const composeEnhancers = composeWithDevTools({
name: `${Platform.OS} - ${new Date()}`
})(applyMiddleware(...middlewares))
const store = createStore(reducer, /* initialState, */ composeEnhancers)
class Root extends React.Component {
render () {
return (
<Provider store={store}>
<App />
</Provider>
)
}
}
export default function () {
return Root
}
|
app/components/ProjectItem.js | DMXL/dm-react-resume | import React from 'react';
const ProjectItem = props => {
const getHighlights = props.data.highlights.map(function(item, index) {
return (<li key={index}>{item}</li>);
});
const getSkills = props.data.skills.map(function(item, index) {
let tagClass = "tag";
/*
const regBack = /^php|^node/i;
const regJs = /^javascript|^jquery/i;
const regCss = /^css|^less|^sass/i;
const regHtml = /^html|^h5/i;
if(regBack.test(item)) {
tagClass += " back";
} else if (regJs.test(item)) {
tagClass += " js";
} else if (regCss.test(item)) {
tagClass += " css";
} else if (regHtml.test(item)) {
tagClass += " html"
}
*/
return (<span key={index} className={tagClass}>| {item}</span>);
});
let link = null;
if(props.data.link) {
link = <a href={props.data.link} target="_blank"><i className="fa fa-link m-l-1" aria-hidden="true"></i></a>;
}
return (
<div className="projectItem">
<h3><b>{props.data.name}</b></h3>{link}
<div className="tagGroup">{getSkills}</div>
<ul>{getHighlights}</ul>
</div>
);
};
export default ProjectItem;
|
client/src/views/git-importer/entry.js | praekelt/molo | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './store';
import GitImporterContainer from './containers/git-importer';
let store = configureStore();
render(
<Provider store={store}>
<GitImporterContainer/>
</Provider>,
document.getElementById('mountpoint')
);
|
src/svg-icons/editor/multiline-chart.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMultilineChart = (props) => (
<SvgIcon {...props}>
<path d="M22 6.92l-1.41-1.41-2.85 3.21C15.68 6.4 12.83 5 9.61 5 6.72 5 4.07 6.16 2 8l1.42 1.42C5.12 7.93 7.27 7 9.61 7c2.74 0 5.09 1.26 6.77 3.24l-2.88 3.24-4-4L2 16.99l1.5 1.5 6-6.01 4 4 4.05-4.55c.75 1.35 1.25 2.9 1.44 4.55H21c-.22-2.3-.95-4.39-2.04-6.14L22 6.92z"/>
</SvgIcon>
);
EditorMultilineChart = pure(EditorMultilineChart);
EditorMultilineChart.displayName = 'EditorMultilineChart';
EditorMultilineChart.muiName = 'SvgIcon';
export default EditorMultilineChart;
|
node_modules/react-bootstrap/es/Breadcrumb.js | okristian1/react-info | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import BreadcrumbItem from './BreadcrumbItem';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var Breadcrumb = function (_React$Component) {
_inherits(Breadcrumb, _React$Component);
function Breadcrumb() {
_classCallCheck(this, Breadcrumb);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Breadcrumb.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('ol', _extends({}, elementProps, {
role: 'navigation',
'aria-label': 'breadcrumbs',
className: classNames(className, classes)
}));
};
return Breadcrumb;
}(React.Component);
Breadcrumb.Item = BreadcrumbItem;
export default bsClass('breadcrumb', Breadcrumb); |
src/CodeBlock.js | zugarzeeker/zugarzeeker.github.io | import React from 'react'
const CodeBlock = ({ start, end, className, children }) => (
<span className={className}>
<span className="start">{start}</span>
<span className="content">{children}</span>
<span className="end">{end}</span>
</span>
)
export default CodeBlock
|
components/Brick.js | brh55/react-native-masonry | import React, { Component } from 'react';
import { View, Image, TouchableHighlight } from 'react-native';
import Injector from 'react-native-injectable-component';
export default function Brick (props) {
// Avoid margins for first element
const image = (props.onPress) ? _getTouchableUnit(props, props.gutter) : _getImageTag(props, props.gutter);
const footer = (props.renderFooter) ? props.renderFooter(props.data) : null;
const header = (props.renderHeader) ? props.renderHeader(props.data) : null;
return (
<View key={props.brickKey}>
{header}
{image}
{footer}
</View>
);
}
// _getImageTag :: Image, Gutter -> ImageTag
export function _getImageTag (props, gutter = 0) {
const imageProps = {
key: props.uri,
source: {
uri: props.uri
},
data: {
...props.data
},
resizeMethod: 'auto',
style: {
width: props.width,
height: props.height,
marginTop: gutter,
...props.imageContainerStyle
}
};
return (
<Injector
defaultComponent={Image}
defaultProps={imageProps}
injectant={props.customImageComponent}
injectantProps={props.customImageProps} />
);
}
// _getTouchableUnit :: Image, Number -> TouchableTag
export function _getTouchableUnit (image, gutter = 0) {
return (
<TouchableHighlight
key={image.uri}
onPress={() => image.onPress(image.data)}>
<View>
{ _getImageTag(image, gutter) }
</View>
</TouchableHighlight>
);
}
|
src/svg-icons/av/mic.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvMic = (props) => (
<SvgIcon {...props}>
<path d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/>
</SvgIcon>
);
AvMic = pure(AvMic);
AvMic.displayName = 'AvMic';
export default AvMic;
|
client/modules/Quiz/__tests__/QuizPanelItem.spec.js | Muisti/muisti | import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { QuizPanelItem } from '../components/QuizPanelItem';
import { mountWithIntl, shallowWithIntl } from '../../../util/react-intl-test-helper';
import * as QuizActions from '../QuizActions';
const quiz = {cuid: '3284723894', question: 'Question?', index: 0, options: [
{text: 'False', answer: false, checked: false},
{text: 'True', answer: true, checked: true},
{text: 'False', answer: false, checked: false}
]};
test('QuizPanelItem renders properly', t => {
const wrapper = mountWithIntl(
<QuizPanelItem quiz={quiz}/>
);
t.is(wrapper.find('div').length, 6);
t.is(wrapper.find('span').length, 6);
t.is(wrapper.find('Button').length, 2);
t.is(wrapper.find('QuizItemOption').length, quiz.options.length);
wrapper.unmount();
});
|
packages/material-ui-icons/src/SettingsEthernet.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M7.77 6.76L6.23 5.48.82 12l5.41 6.52 1.54-1.28L3.42 12l4.35-5.24zM7 13h2v-2H7v2zm10-2h-2v2h2v-2zm-6 2h2v-2h-2v2zm6.77-7.52l-1.54 1.28L20.58 12l-4.35 5.24 1.54 1.28L23.18 12l-5.41-6.52z" /></g>
, 'SettingsEthernet');
|
ajax/libs/analytics.js/2.8.10/analytics.js | brix/cdnjs | (function umd(require){
if ('object' == typeof exports) {
module.exports = require('1');
} else if ('function' == typeof define && define.amd) {
define(function(){ return require('1'); });
} else {
this['analytics'] = require('1');
}
})((function outer(modules, cache, entries){
/**
* Global
*/
var global = (function(){ return this; })();
/**
* Require `name`.
*
* @param {String} name
* @param {Boolean} jumped
* @api public
*/
function require(name, jumped){
if (cache[name]) return cache[name].exports;
if (modules[name]) return call(name, require);
throw new Error('cannot find module "' + name + '"');
}
/**
* Call module `id` and cache it.
*
* @param {Number} id
* @param {Function} require
* @return {Function}
* @api private
*/
function call(id, require){
var m = cache[id] = { exports: {} };
var mod = modules[id];
var name = mod[2];
var fn = mod[0];
fn.call(m.exports, function(req){
var dep = modules[id][1][req];
return require(dep ? dep : req);
}, m, m.exports, outer, modules, cache, entries);
// expose as `name`.
if (name) cache[name] = cache[id];
return cache[id].exports;
}
/**
* Require all entries exposing them on global if needed.
*/
for (var id in entries) {
if (entries[id]) {
global[entries[id]] = require(id);
} else {
require(id);
}
}
/**
* Duo flag.
*/
require.duo = true;
/**
* Expose cache.
*/
require.cache = cache;
/**
* Expose modules
*/
require.modules = modules;
/**
* Return newest require.
*/
return require;
})({
1: [function(require, module, exports) {
/**
* Analytics.js
*
* (C) 2013 Segment.io Inc.
*/
var _analytics = window.analytics;
var Integrations = require('analytics.js-integrations');
var Analytics = require('./analytics');
var each = require('each');
/**
* Expose the `analytics` singleton.
*/
var analytics = module.exports = exports = new Analytics();
/**
* Expose require
*/
analytics.require = require;
/**
* Expose `VERSION`.
*/
exports.VERSION = require('../bower.json').version;
/**
* Add integrations.
*/
each(Integrations, function (name, Integration) {
analytics.use(Integration);
});
}, {"analytics.js-integrations":2,"./analytics":3,"each":4,"../bower.json":5}],
2: [function(require, module, exports) {
/**
* Module dependencies.
*/
var each = require('each');
var plugins = require('./integrations.js');
/**
* Expose the integrations, using their own `name` from their `prototype`.
*/
each(plugins, function(plugin){
var name = (plugin.Integration || plugin).prototype.name;
exports[name] = plugin;
});
}, {"each":4,"./integrations.js":6}],
4: [function(require, module, exports) {
/**
* Module dependencies.
*/
var type = require('type');
/**
* HOP reference.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Iterate the given `obj` and invoke `fn(val, i)`.
*
* @param {String|Array|Object} obj
* @param {Function} fn
* @api public
*/
module.exports = function(obj, fn){
switch (type(obj)) {
case 'array':
return array(obj, fn);
case 'object':
if ('number' == typeof obj.length) return array(obj, fn);
return object(obj, fn);
case 'string':
return string(obj, fn);
}
};
/**
* Iterate string chars.
*
* @param {String} obj
* @param {Function} fn
* @api private
*/
function string(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj.charAt(i), i);
}
}
/**
* Iterate object keys.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function object(obj, fn) {
for (var key in obj) {
if (has.call(obj, key)) {
fn(key, obj[key]);
}
}
}
/**
* Iterate array-ish.
*
* @param {Array|Object} obj
* @param {Function} fn
* @api private
*/
function array(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj[i], i);
}
}
}, {"type":7}],
7: [function(require, module, exports) {
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object Error]': return 'error';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val !== val) return 'nan';
if (val && val.nodeType === 1) return 'element';
val = val.valueOf
? val.valueOf()
: Object.prototype.valueOf.apply(val)
return typeof val;
};
}, {}],
6: [function(require, module, exports) {
/**
* DON'T EDIT THIS FILE. It's automatically generated!
*/
module.exports = [
require('./lib/adroll'),
require('./lib/adwords'),
require('./lib/alexa'),
require('./lib/amplitude'),
require('./lib/appcues'),
require('./lib/atatus'),
require('./lib/autosend'),
require('./lib/awesm'),
require('./lib/bing-ads'),
require('./lib/blueshift'),
require('./lib/bronto'),
require('./lib/bugherd'),
require('./lib/bugsnag'),
require('./lib/chartbeat'),
require('./lib/churnbee'),
require('./lib/clicktale'),
require('./lib/clicky'),
require('./lib/comscore'),
require('./lib/crazy-egg'),
require('./lib/curebit'),
require('./lib/customerio'),
require('./lib/drip'),
require('./lib/errorception'),
require('./lib/evergage'),
require('./lib/extole'),
require('./lib/facebook-conversion-tracking'),
require('./lib/foxmetrics'),
require('./lib/frontleaf'),
require('./lib/fullstory'),
require('./lib/gauges'),
require('./lib/get-satisfaction'),
require('./lib/google-analytics'),
require('./lib/google-tag-manager'),
require('./lib/gosquared'),
require('./lib/heap'),
require('./lib/hellobar'),
require('./lib/hittail'),
require('./lib/hubspot'),
require('./lib/improvely'),
require('./lib/insidevault'),
require('./lib/inspectlet'),
require('./lib/intercom'),
require('./lib/keen-io'),
require('./lib/kenshoo'),
require('./lib/kissmetrics'),
require('./lib/klaviyo'),
require('./lib/livechat'),
require('./lib/lucky-orange'),
require('./lib/lytics'),
require('./lib/mixpanel'),
require('./lib/mojn'),
require('./lib/mouseflow'),
require('./lib/mousestats'),
require('./lib/navilytics'),
require('./lib/nudgespot'),
require('./lib/olark'),
require('./lib/optimizely'),
require('./lib/perfect-audience'),
require('./lib/pingdom'),
require('./lib/piwik'),
require('./lib/preact'),
require('./lib/qualaroo'),
require('./lib/quantcast'),
require('./lib/rollbar'),
require('./lib/saasquatch'),
require('./lib/satismeter'),
require('./lib/segmentio'),
require('./lib/sentry'),
require('./lib/snapengage'),
require('./lib/spinnakr'),
require('./lib/tapstream'),
require('./lib/trakio'),
require('./lib/twitter-ads'),
require('./lib/userlike'),
require('./lib/uservoice'),
require('./lib/vero'),
require('./lib/visual-website-optimizer'),
require('./lib/webengage'),
require('./lib/woopra'),
require('./lib/yandex-metrica')
];
}, {"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/atatus":13,"./lib/autosend":14,"./lib/awesm":15,"./lib/bing-ads":16,"./lib/blueshift":17,"./lib/bronto":18,"./lib/bugherd":19,"./lib/bugsnag":20,"./lib/chartbeat":21,"./lib/churnbee":22,"./lib/clicktale":23,"./lib/clicky":24,"./lib/comscore":25,"./lib/crazy-egg":26,"./lib/curebit":27,"./lib/customerio":28,"./lib/drip":29,"./lib/errorception":30,"./lib/evergage":31,"./lib/extole":32,"./lib/facebook-conversion-tracking":33,"./lib/foxmetrics":34,"./lib/frontleaf":35,"./lib/fullstory":36,"./lib/gauges":37,"./lib/get-satisfaction":38,"./lib/google-analytics":39,"./lib/google-tag-manager":40,"./lib/gosquared":41,"./lib/heap":42,"./lib/hellobar":43,"./lib/hittail":44,"./lib/hubspot":45,"./lib/improvely":46,"./lib/insidevault":47,"./lib/inspectlet":48,"./lib/intercom":49,"./lib/keen-io":50,"./lib/kenshoo":51,"./lib/kissmetrics":52,"./lib/klaviyo":53,"./lib/livechat":54,"./lib/lucky-orange":55,"./lib/lytics":56,"./lib/mixpanel":57,"./lib/mojn":58,"./lib/mouseflow":59,"./lib/mousestats":60,"./lib/navilytics":61,"./lib/nudgespot":62,"./lib/olark":63,"./lib/optimizely":64,"./lib/perfect-audience":65,"./lib/pingdom":66,"./lib/piwik":67,"./lib/preact":68,"./lib/qualaroo":69,"./lib/quantcast":70,"./lib/rollbar":71,"./lib/saasquatch":72,"./lib/satismeter":73,"./lib/segmentio":74,"./lib/sentry":75,"./lib/snapengage":76,"./lib/spinnakr":77,"./lib/tapstream":78,"./lib/trakio":79,"./lib/twitter-ads":80,"./lib/userlike":81,"./lib/uservoice":82,"./lib/vero":83,"./lib/visual-website-optimizer":84,"./lib/webengage":85,"./lib/woopra":86,"./lib/yandex-metrica":87}],
8: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var snake = require('to-snake-case');
var useHttps = require('use-https');
var each = require('each');
var is = require('is');
var del = require('obj-case').del;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `AdRoll` integration.
*/
var AdRoll = module.exports = integration('AdRoll')
.assumesPageview()
.global('__adroll_loaded')
.global('adroll_adv_id')
.global('adroll_pix_id')
.global('adroll_custom_data')
.option('advId', '')
.option('pixId', '')
.tag('http', '<script src="http://a.adroll.com/j/roundtrip.js">')
.tag('https', '<script src="https://s.adroll.com/j/roundtrip.js">')
.mapping('events');
/**
* Initialize.
*
* http://support.adroll.com/getting-started-in-4-easy-steps/#step-one
* http://support.adroll.com/enhanced-conversion-tracking/
*
* @param {Object} page
*/
AdRoll.prototype.initialize = function(page){
window.adroll_adv_id = this.options.advId;
window.adroll_pix_id = this.options.pixId;
window.__adroll_loaded = true;
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
AdRoll.prototype.loaded = function(){
return window.__adroll;
};
/**
* Page.
*
* http://support.adroll.com/segmenting-clicks/
*
* @param {Page} page
*/
AdRoll.prototype.page = function(page){
var name = page.fullName();
this.track(page.track(name));
};
/**
* Track.
*
* @param {Track} track
*/
AdRoll.prototype.track = function(track){
var event = track.event();
var user = this.analytics.user();
var events = this.events(event);
var total = track.revenue() || track.total() || 0;
var orderId = track.orderId() || 0;
var productId = track.id();
var sku = track.sku();
var customProps = track.properties();
var data = {};
if (user.id()) data.user_id = user.id();
if (orderId) data.order_id = orderId;
if (productId) data.product_id = productId;
if (sku) data.sku = sku;
if (total) data.adroll_conversion_value_in_dollars = total;
del(customProps, "revenue");
del(customProps, "total");
del(customProps, "orderId");
del(customProps, "id");
del(customProps, "sku");
if (!is.empty(customProps)) data.adroll_custom_data = customProps;
each(events, function(event){
// the adroll interface only allows for
// segment names which are snake cased.
data.adroll_segments = snake(event);
window.__adroll.record_user(data);
});
// no events found
if (!events.length) {
data.adroll_segments = snake(event);
window.__adroll.record_user(data);
}
};
}, {"analytics.js-integration":88,"to-snake-case":89,"use-https":90,"each":4,"is":91,"obj-case":92}],
88: [function(require, module, exports) {
/**
* Module dependencies.
*/
var bind = require('bind');
var callback = require('callback');
var clone = require('clone');
var debug = require('debug');
var defaults = require('defaults');
var protos = require('./protos');
var slug = require('slug');
var statics = require('./statics');
/**
* Expose `createIntegration`.
*/
module.exports = createIntegration;
/**
* Create a new `Integration` constructor.
*
* @param {String} name
* @return {Function} Integration
*/
function createIntegration(name){
/**
* Initialize a new `Integration`.
*
* @param {Object} options
*/
function Integration(options){
if (options && options.addIntegration) {
// plugin
return options.addIntegration(Integration);
}
this.debug = debug('analytics:integration:' + slug(name));
this.options = defaults(clone(options) || {}, this.defaults);
this._queue = [];
this.once('ready', bind(this, this.flush));
Integration.emit('construct', this);
this.ready = bind(this, this.ready);
this._wrapInitialize();
this._wrapPage();
this._wrapTrack();
}
Integration.prototype.defaults = {};
Integration.prototype.globals = [];
Integration.prototype.templates = {};
Integration.prototype.name = name;
for (var key in statics) Integration[key] = statics[key];
for (var key in protos) Integration.prototype[key] = protos[key];
return Integration;
}
}, {"bind":93,"callback":94,"clone":95,"debug":96,"defaults":97,"./protos":98,"slug":99,"./statics":100}],
93: [function(require, module, exports) {
var bind = require('bind')
, bindAll = require('bind-all');
/**
* Expose `bind`.
*/
module.exports = exports = bind;
/**
* Expose `bindAll`.
*/
exports.all = bindAll;
/**
* Expose `bindMethods`.
*/
exports.methods = bindMethods;
/**
* Bind `methods` on `obj` to always be called with the `obj` as context.
*
* @param {Object} obj
* @param {String} methods...
*/
function bindMethods (obj, methods) {
methods = [].slice.call(arguments, 1);
for (var i = 0, method; method = methods[i]; i++) {
obj[method] = bind(obj, obj[method]);
}
return obj;
}
}, {"bind":101,"bind-all":102}],
101: [function(require, module, exports) {
/**
* Slice reference.
*/
var slice = [].slice;
/**
* Bind `obj` to `fn`.
*
* @param {Object} obj
* @param {Function|String} fn or string
* @return {Function}
* @api public
*/
module.exports = function(obj, fn){
if ('string' == typeof fn) fn = obj[fn];
if ('function' != typeof fn) throw new Error('bind() requires a function');
var args = slice.call(arguments, 2);
return function(){
return fn.apply(obj, args.concat(slice.call(arguments)));
}
};
}, {}],
102: [function(require, module, exports) {
try {
var bind = require('bind');
var type = require('type');
} catch (e) {
var bind = require('bind-component');
var type = require('type-component');
}
module.exports = function (obj) {
for (var key in obj) {
var val = obj[key];
if (type(val) === 'function') obj[key] = bind(obj, obj[key]);
}
return obj;
};
}, {"bind":101,"type":7}],
94: [function(require, module, exports) {
var next = require('next-tick');
/**
* Expose `callback`.
*/
module.exports = callback;
/**
* Call an `fn` back synchronously if it exists.
*
* @param {Function} fn
*/
function callback (fn) {
if ('function' === typeof fn) fn();
}
/**
* Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the
* `fn` will be called on next tick.
*
* @param {Function} fn
* @param {Number} wait (optional)
*/
callback.async = function (fn, wait) {
if ('function' !== typeof fn) return;
if (!wait) return next(fn);
setTimeout(fn, wait);
};
/**
* Symmetry.
*/
callback.sync = callback;
}, {"next-tick":103}],
103: [function(require, module, exports) {
"use strict"
if (typeof setImmediate == 'function') {
module.exports = function(f){ setImmediate(f) }
}
// legacy node.js
else if (typeof process != 'undefined' && typeof process.nextTick == 'function') {
module.exports = process.nextTick
}
// fallback for other environments / postMessage behaves badly on IE8
else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) {
module.exports = function(f){ setTimeout(f) };
} else {
var q = [];
window.addEventListener('message', function(){
var i = 0;
while (i < q.length) {
try { q[i++](); }
catch (e) {
q = q.slice(i);
window.postMessage('tic!', '*');
throw e;
}
}
q.length = 0;
}, true);
module.exports = function(fn){
if (!q.length) window.postMessage('tic!', '*');
q.push(fn);
}
}
}, {}],
95: [function(require, module, exports) {
/**
* Module dependencies.
*/
var type;
try {
type = require('type');
} catch(e){
type = require('type-component');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
}, {"type":7}],
96: [function(require, module, exports) {
if ('undefined' == typeof window) {
module.exports = require('./lib/debug');
} else {
module.exports = require('./debug');
}
}, {"./lib/debug":104,"./debug":105}],
104: [function(require, module, exports) {
/**
* Module dependencies.
*/
var tty = require('tty');
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Enabled debuggers.
*/
var names = []
, skips = [];
(process.env.DEBUG || '')
.split(/[\s,]+/)
.forEach(function(name){
name = name.replace('*', '.*?');
if (name[0] === '-') {
skips.push(new RegExp('^' + name.substr(1) + '$'));
} else {
names.push(new RegExp('^' + name + '$'));
}
});
/**
* Colors.
*/
var colors = [6, 2, 3, 4, 5, 1];
/**
* Previous debug() call.
*/
var prev = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Is stdout a TTY? Colored output is disabled when `true`.
*/
var isatty = tty.isatty(2);
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function color() {
return colors[prevColor++ % colors.length];
}
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
function humanize(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
}
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
function disabled(){}
disabled.enabled = false;
var match = skips.some(function(re){
return re.test(name);
});
if (match) return disabled;
match = names.some(function(re){
return re.test(name);
});
if (!match) return disabled;
var c = color();
function colored(fmt) {
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (prev[name] || curr);
prev[name] = curr;
fmt = ' \u001b[9' + c + 'm' + name + ' '
+ '\u001b[3' + c + 'm\u001b[90m'
+ fmt + '\u001b[3' + c + 'm'
+ ' +' + humanize(ms) + '\u001b[0m';
console.error.apply(this, arguments);
}
function plain(fmt) {
fmt = coerce(fmt);
fmt = new Date().toUTCString()
+ ' ' + name + ' ' + fmt;
console.error.apply(this, arguments);
}
colored.enabled = plain.enabled = true;
return isatty || process.env.DEBUG_COLORS
? colored
: plain;
}
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
}, {}],
105: [function(require, module, exports) {
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
try {
localStorage.debug = name;
} catch(e){}
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
// persist
try {
if (window.localStorage) debug.enable(localStorage.debug);
} catch(e){}
}, {}],
97: [function(require, module, exports) {
'use strict';
/**
* Merge default values.
*
* @param {Object} dest
* @param {Object} defaults
* @return {Object}
* @api public
*/
var defaults = function (dest, src, recursive) {
for (var prop in src) {
if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) {
dest[prop] = defaults(dest[prop], src[prop], true);
} else if (! (prop in dest)) {
dest[prop] = src[prop];
}
}
return dest;
};
/**
* Expose `defaults`.
*/
module.exports = defaults;
}, {}],
98: [function(require, module, exports) {
/**
* Module dependencies.
*/
var loadScript = require('load-script');
var loadIframe = require('load-iframe');
var events = require('analytics-events');
var normalize = require('to-no-case');
var callback = require('callback');
var Emitter = require('emitter');
var tick = require('next-tick');
var after = require('after');
var each = require('each');
var type = require('type');
var fmt = require('fmt');
/**
* Noop.
*/
function noop(){}
/**
* Window defaults.
*/
var setTimeout = window.setTimeout;
var setInterval = window.setInterval;
var onerror = window.onerror;
var onload = null;
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Initialize.
*/
exports.initialize = function(){
var ready = this.ready;
tick(ready);
};
/**
* Loaded?
*
* @return {Boolean}
* @api private
*/
exports.loaded = function(){
return false;
};
/**
* Page.
*
* @param {Page} page
*/
exports.page = function(page){};
/**
* Track.
*
* @param {Track} track
*/
exports.track = function(track){};
/**
* Get events that match `str`.
*
* Examples:
*
* events = { my_event: 'a4991b88' }
* .map(events, 'My Event');
* // => ["a4991b88"]
* .map(events, 'whatever');
* // => []
*
* events = [{ key: 'my event', value: '9b5eb1fa' }]
* .map(events, 'my_event');
* // => ["9b5eb1fa"]
* .map(events, 'whatever');
* // => []
*
* @param {String} str
* @return {Array}
* @api public
*/
exports.map = function(obj, str){
var a = normalize(str);
var ret = [];
// noop
if (!obj) return ret;
// object
if ('object' == type(obj)) {
for (var k in obj) {
var item = obj[k];
var b = normalize(k);
if (b == a) ret.push(item);
}
}
// array
if ('array' == type(obj)) {
if (!obj.length) return ret;
if (!obj[0].key) return ret;
for (var i = 0; i < obj.length; ++i) {
var item = obj[i];
var b = normalize(item.key);
if (b == a) ret.push(item.value);
}
}
return ret;
};
/**
* Invoke a `method` that may or may not exist on the prototype with `args`,
* queueing or not depending on whether the integration is "ready". Don't
* trust the method call, since it contains integration party code.
*
* @param {String} method
* @param {Mixed} args...
* @api private
*/
exports.invoke = function(method){
if (!this[method]) return;
var args = [].slice.call(arguments, 1);
if (!this._ready) return this.queue(method, args);
var ret;
try {
this.debug('%s with %o', method, args);
ret = this[method].apply(this, args);
} catch (e) {
this.debug('error %o calling %s with %o', e, method, args);
}
return ret;
};
/**
* Queue a `method` with `args`. If the integration assumes an initial
* pageview, then let the first call to `page` pass through.
*
* @param {String} method
* @param {Array} args
* @api private
*/
exports.queue = function(method, args){
if ('page' == method && this._assumesPageview && !this._initialized) {
return this.page.apply(this, args);
}
this._queue.push({ method: method, args: args });
};
/**
* Flush the internal queue.
*
* @api private
*/
exports.flush = function(){
this._ready = true;
var call;
while (call = this._queue.shift()) this[call.method].apply(this, call.args);
};
/**
* Reset the integration, removing its global variables.
*
* @api private
*/
exports.reset = function(){
for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined;
window.setTimeout = setTimeout;
window.setInterval = setInterval;
window.onerror = onerror;
window.onload = onload;
};
/**
* Load a tag by `name`.
*
* @param {String} name
* @param {Function} [fn]
*/
exports.load = function(name, locals, fn){
if ('function' == typeof name) fn = name, locals = null, name = null;
if (name && 'object' == typeof name) fn = locals, locals = name, name = null;
if ('function' == typeof locals) fn = locals, locals = null;
name = name || 'library';
locals = locals || {};
locals = this.locals(locals);
var template = this.templates[name];
if (!template) throw new Error(fmt('template "%s" not defined.', name));
var attrs = render(template, locals);
var fn = fn || noop;
var self = this;
var el;
switch (template.type) {
case 'img':
attrs.width = 1;
attrs.height = 1;
el = loadImage(attrs, fn);
break;
case 'script':
el = loadScript(attrs, function(err){
if (!err) return fn();
self.debug('error loading "%s" error="%s"', self.name, err);
});
// TODO: hack until refactoring load-script
delete attrs.src;
each(attrs, function(key, val){
el.setAttribute(key, val);
});
break;
case 'iframe':
el = loadIframe(attrs, fn);
break;
}
return el;
};
/**
* Locals for tag templates.
*
* By default it includes a cache buster,
* and all of the options.
*
* @param {Object} [locals]
* @return {Object}
*/
exports.locals = function(locals){
locals = locals || {};
var cache = Math.floor(new Date().getTime() / 3600000);
if (!locals.hasOwnProperty('cache')) locals.cache = cache;
each(this.options, function(key, val){
if (!locals.hasOwnProperty(key)) locals[key] = val;
});
return locals;
};
/**
* Simple way to emit ready.
*/
exports.ready = function(){
this.emit('ready');
};
/**
* Wrap the initialize method in an exists check, so we don't have to do it for
* every single integration.
*
* @api private
*/
exports._wrapInitialize = function(){
var initialize = this.initialize;
this.initialize = function(){
this.debug('initialize');
this._initialized = true;
var ret = initialize.apply(this, arguments);
this.emit('initialize');
return ret;
};
if (this._assumesPageview) this.initialize = after(2, this.initialize);
};
/**
* Wrap the page method to call `initialize` instead if the integration assumes
* a pageview.
*
* @api private
*/
exports._wrapPage = function(){
var page = this.page;
this.page = function(){
if (this._assumesPageview && !this._initialized) {
return this.initialize.apply(this, arguments);
}
return page.apply(this, arguments);
};
};
/**
* Wrap the track method to call other ecommerce methods if
* available depending on the `track.event()`.
*
* @api private
*/
exports._wrapTrack = function(){
var t = this.track;
this.track = function(track){
var event = track.event();
var called;
var ret;
for (var method in events) {
var regexp = events[method];
if (!this[method]) continue;
if (!regexp.test(event)) continue;
ret = this[method].apply(this, arguments);
called = true;
break;
}
if (!called) ret = t.apply(this, arguments);
return ret;
};
};
function loadImage(attrs, fn) {
fn = fn || function(){};
var img = new Image;
img.onerror = error(fn, 'failed to load pixel', img);
img.onload = function(){ fn(); };
img.src = attrs.src;
img.width = 1;
img.height = 1;
return img;
}
function error(fn, message, img){
return function(e){
e = e || window.event;
var err = new Error(message);
err.event = e;
err.source = img;
fn(err);
};
}
/**
* Render template + locals into an `attrs` object.
*
* @param {Object} template
* @param {Object} locals
* @return {Object}
*/
function render(template, locals) {
var attrs = {};
each(template.attrs, function(key, val){
attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){
return locals[$1];
});
});
return attrs;
}
}, {"load-script":106,"load-iframe":107,"analytics-events":108,"to-no-case":109,"callback":94,"emitter":110,"next-tick":103,"after":111,"each":112,"type":113,"fmt":114}],
106: [function(require, module, exports) {
/**
* Module dependencies.
*/
var onload = require('script-onload');
var tick = require('next-tick');
var type = require('type');
/**
* Expose `loadScript`.
*
* @param {Object} options
* @param {Function} fn
* @api public
*/
module.exports = function loadScript(options, fn){
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if ('string' == type(options)) options = { src : options };
var https = document.location.protocol === 'https:' ||
document.location.protocol === 'chrome-extension:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = https ? 'https:' + options.src : 'http:' + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) options.src = options.https;
else if (!https && options.http) options.src = options.http;
// Make the `<script>` element and insert it before the first script on the
// page, which is guaranteed to exist since this Javascript is running.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = options.src;
// If we have a fn, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if ('function' == type(fn)) {
onload(script, fn);
}
tick(function(){
// Append after event listeners are attached for IE.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
});
// Return the script element in case they want to do anything special, like
// give it an ID or attributes.
return script;
};
}, {"script-onload":115,"next-tick":103,"type":7}],
115: [function(require, module, exports) {
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
/**
* Invoke `fn(err)` when the given `el` script loads.
*
* @param {Element} el
* @param {Function} fn
* @api public
*/
module.exports = function(el, fn){
return el.addEventListener
? add(el, fn)
: attach(el, fn);
};
/**
* Add event listener to `el`, `fn()`.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function add(el, fn){
el.addEventListener('load', function(_, e){ fn(null, e); }, false);
el.addEventListener('error', function(e){
var err = new Error('script error "' + el.src + '"');
err.event = e;
fn(err);
}, false);
}
/**
* Attach evnet.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function attach(el, fn){
el.attachEvent('onreadystatechange', function(e){
if (!/complete|loaded/.test(el.readyState)) return;
fn(null, e);
});
el.attachEvent('onerror', function(e){
var err = new Error('failed to load the script "' + el.src + '"');
err.event = e || window.event;
fn(err);
});
}
}, {}],
107: [function(require, module, exports) {
/**
* Module dependencies.
*/
var onload = require('script-onload');
var tick = require('next-tick');
var type = require('type');
/**
* Expose `loadScript`.
*
* @param {Object} options
* @param {Function} fn
* @api public
*/
module.exports = function loadIframe(options, fn){
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if ('string' == type(options)) options = { src : options };
var https = document.location.protocol === 'https:' ||
document.location.protocol === 'chrome-extension:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = https ? 'https:' + options.src : 'http:' + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) options.src = options.https;
else if (!https && options.http) options.src = options.http;
// Make the `<iframe>` element and insert it before the first iframe on the
// page, which is guaranteed to exist since this Javaiframe is running.
var iframe = document.createElement('iframe');
iframe.src = options.src;
iframe.width = options.width || 1;
iframe.height = options.height || 1;
iframe.style.display = 'none';
// If we have a fn, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if ('function' == type(fn)) {
onload(iframe, fn);
}
tick(function(){
// Append after event listeners are attached for IE.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(iframe, firstScript);
});
// Return the iframe element in case they want to do anything special, like
// give it an ID or attributes.
return iframe;
};
}, {"script-onload":115,"next-tick":103,"type":7}],
108: [function(require, module, exports) {
module.exports = {
removedProduct: /^[ _]?removed[ _]?product[ _]?$/i,
viewedProduct: /^[ _]?viewed[ _]?product[ _]?$/i,
viewedProductCategory: /^[ _]?viewed[ _]?product[ _]?category[ _]?$/i,
addedProduct: /^[ _]?added[ _]?product[ _]?$/i,
completedOrder: /^[ _]?completed[ _]?order[ _]?$/i,
startedOrder: /^[ _]?started[ _]?order[ _]?$/i,
updatedOrder: /^[ _]?updated[ _]?order[ _]?$/i,
refundedOrder: /^[ _]?refunded?[ _]?order[ _]?$/i,
viewedProductDetails: /^[ _]?viewed[ _]?product[ _]?details?[ _]?$/i,
clickedProduct: /^[ _]?clicked[ _]?product[ _]?$/i,
viewedPromotion: /^[ _]?viewed[ _]?promotion?[ _]?$/i,
clickedPromotion: /^[ _]?clicked[ _]?promotion?[ _]?$/i,
viewedCheckoutStep: /^[ _]?viewed[ _]?checkout[ _]?step[ _]?$/i,
completedCheckoutStep: /^[ _]?completed[ _]?checkout[ _]?step[ _]?$/i
};
}, {}],
109: [function(require, module, exports) {
/**
* Expose `toNoCase`.
*/
module.exports = toNoCase;
/**
* Test whether a string is camel-case.
*/
var hasSpace = /\s/;
var hasSeparator = /[\W_]/;
/**
* Remove any starting case from a `string`, like camel or snake, but keep
* spaces and punctuation that may be important otherwise.
*
* @param {String} string
* @return {String}
*/
function toNoCase (string) {
if (hasSpace.test(string)) return string.toLowerCase();
if (hasSeparator.test(string)) return unseparate(string).toLowerCase();
return uncamelize(string).toLowerCase();
}
/**
* Separator splitter.
*/
var separatorSplitter = /[\W_]+(.|$)/g;
/**
* Un-separate a `string`.
*
* @param {String} string
* @return {String}
*/
function unseparate (string) {
return string.replace(separatorSplitter, function (m, next) {
return next ? ' ' + next : '';
});
}
/**
* Camelcase splitter.
*/
var camelSplitter = /(.)([A-Z]+)/g;
/**
* Un-camelcase a `string`.
*
* @param {String} string
* @return {String}
*/
function uncamelize (string) {
return string.replace(camelSplitter, function (m, previous, uppers) {
return previous + ' ' + uppers.toLowerCase().split('').join(' ');
});
}
}, {}],
110: [function(require, module, exports) {
/**
* Module dependencies.
*/
var index = require('indexof');
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
fn._off = on;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var i = index(callbacks, fn._off || fn);
if (~i) callbacks.splice(i, 1);
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
}, {"indexof":116}],
116: [function(require, module, exports) {
module.exports = function(arr, obj){
if (arr.indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
}, {}],
111: [function(require, module, exports) {
module.exports = function after (times, func) {
// After 0, really?
if (times <= 0) return func();
// That's more like it.
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
}, {}],
112: [function(require, module, exports) {
/**
* Module dependencies.
*/
try {
var type = require('type');
} catch (err) {
var type = require('component-type');
}
var toFunction = require('to-function');
/**
* HOP reference.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Iterate the given `obj` and invoke `fn(val, i)`
* in optional context `ctx`.
*
* @param {String|Array|Object} obj
* @param {Function} fn
* @param {Object} [ctx]
* @api public
*/
module.exports = function(obj, fn, ctx){
fn = toFunction(fn);
ctx = ctx || this;
switch (type(obj)) {
case 'array':
return array(obj, fn, ctx);
case 'object':
if ('number' == typeof obj.length) return array(obj, fn, ctx);
return object(obj, fn, ctx);
case 'string':
return string(obj, fn, ctx);
}
};
/**
* Iterate string chars.
*
* @param {String} obj
* @param {Function} fn
* @param {Object} ctx
* @api private
*/
function string(obj, fn, ctx) {
for (var i = 0; i < obj.length; ++i) {
fn.call(ctx, obj.charAt(i), i);
}
}
/**
* Iterate object keys.
*
* @param {Object} obj
* @param {Function} fn
* @param {Object} ctx
* @api private
*/
function object(obj, fn, ctx) {
for (var key in obj) {
if (has.call(obj, key)) {
fn.call(ctx, key, obj[key]);
}
}
}
/**
* Iterate array-ish.
*
* @param {Array|Object} obj
* @param {Function} fn
* @param {Object} ctx
* @api private
*/
function array(obj, fn, ctx) {
for (var i = 0; i < obj.length; ++i) {
fn.call(ctx, obj[i], i);
}
}
}, {"type":113,"component-type":113,"to-function":117}],
113: [function(require, module, exports) {
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Function]': return 'function';
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object String]': return 'string';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val && val.nodeType === 1) return 'element';
if (val === Object(val)) return 'object';
return typeof val;
};
}, {}],
117: [function(require, module, exports) {
/**
* Module Dependencies
*/
var expr;
try {
expr = require('props');
} catch(e) {
expr = require('component-props');
}
/**
* Expose `toFunction()`.
*/
module.exports = toFunction;
/**
* Convert `obj` to a `Function`.
*
* @param {Mixed} obj
* @return {Function}
* @api private
*/
function toFunction(obj) {
switch ({}.toString.call(obj)) {
case '[object Object]':
return objectToFunction(obj);
case '[object Function]':
return obj;
case '[object String]':
return stringToFunction(obj);
case '[object RegExp]':
return regexpToFunction(obj);
default:
return defaultToFunction(obj);
}
}
/**
* Default to strict equality.
*
* @param {Mixed} val
* @return {Function}
* @api private
*/
function defaultToFunction(val) {
return function(obj){
return val === obj;
};
}
/**
* Convert `re` to a function.
*
* @param {RegExp} re
* @return {Function}
* @api private
*/
function regexpToFunction(re) {
return function(obj){
return re.test(obj);
};
}
/**
* Convert property `str` to a function.
*
* @param {String} str
* @return {Function}
* @api private
*/
function stringToFunction(str) {
// immediate such as "> 20"
if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str);
// properties such as "name.first" or "age > 18" or "age > 18 && age < 36"
return new Function('_', 'return ' + get(str));
}
/**
* Convert `object` to a function.
*
* @param {Object} object
* @return {Function}
* @api private
*/
function objectToFunction(obj) {
var match = {};
for (var key in obj) {
match[key] = typeof obj[key] === 'string'
? defaultToFunction(obj[key])
: toFunction(obj[key]);
}
return function(val){
if (typeof val !== 'object') return false;
for (var key in match) {
if (!(key in val)) return false;
if (!match[key](val[key])) return false;
}
return true;
};
}
/**
* Built the getter function. Supports getter style functions
*
* @param {String} str
* @return {String}
* @api private
*/
function get(str) {
var props = expr(str);
if (!props.length) return '_.' + str;
var val, i, prop;
for (i = 0; i < props.length; i++) {
prop = props[i];
val = '_.' + prop;
val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")";
// mimic negative lookbehind to avoid problems with nested properties
str = stripNested(prop, str, val);
}
return str;
}
/**
* Mimic negative lookbehind to avoid problems with nested properties.
*
* See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
*
* @param {String} prop
* @param {String} str
* @param {String} val
* @return {String}
* @api private
*/
function stripNested (prop, str, val) {
return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) {
return $1 ? $0 : val;
});
}
}, {"props":118,"component-props":118}],
118: [function(require, module, exports) {
/**
* Global Names
*/
var globals = /\b(this|Array|Date|Object|Math|JSON)\b/g;
/**
* Return immediate identifiers parsed from `str`.
*
* @param {String} str
* @param {String|Function} map function or prefix
* @return {Array}
* @api public
*/
module.exports = function(str, fn){
var p = unique(props(str));
if (fn && 'string' == typeof fn) fn = prefixed(fn);
if (fn) return map(str, p, fn);
return p;
};
/**
* Return immediate identifiers in `str`.
*
* @param {String} str
* @return {Array}
* @api private
*/
function props(str) {
return str
.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g, '')
.replace(globals, '')
.match(/[$a-zA-Z_]\w*/g)
|| [];
}
/**
* Return `str` with `props` mapped with `fn`.
*
* @param {String} str
* @param {Array} props
* @param {Function} fn
* @return {String}
* @api private
*/
function map(str, props, fn) {
var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;
return str.replace(re, function(_){
if ('(' == _[_.length - 1]) return fn(_);
if (!~props.indexOf(_)) return _;
return fn(_);
});
}
/**
* Return unique array.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
function unique(arr) {
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (~ret.indexOf(arr[i])) continue;
ret.push(arr[i]);
}
return ret;
}
/**
* Map with prefix `str`.
*/
function prefixed(str) {
return function(_){
return str + _;
};
}
}, {}],
114: [function(require, module, exports) {
/**
* toString.
*/
var toString = window.JSON
? JSON.stringify
: function(_){ return String(_); };
/**
* Export `fmt`
*/
module.exports = fmt;
/**
* Formatters
*/
fmt.o = toString;
fmt.s = String;
fmt.d = parseInt;
/**
* Format the given `str`.
*
* @param {String} str
* @param {...} args
* @return {String}
* @api public
*/
function fmt(str){
var args = [].slice.call(arguments, 1);
var j = 0;
return str.replace(/%([a-z])/gi, function(_, f){
return fmt[f]
? fmt[f](args[j++])
: _ + f;
});
}
}, {}],
99: [function(require, module, exports) {
/**
* Generate a slug from the given `str`.
*
* example:
*
* generate('foo bar');
* // > foo-bar
*
* @param {String} str
* @param {Object} options
* @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g`
* @config {String} [separator] separator to insert, defaulted to `-`
* @return {String}
*/
module.exports = function (str, options) {
options || (options = {});
return str.toLowerCase()
.replace(options.replace || /[^a-z0-9]/g, ' ')
.replace(/^ +| +$/g, '')
.replace(/ +/g, options.separator || '-')
};
}, {}],
100: [function(require, module, exports) {
/**
* Module dependencies.
*/
var after = require('after');
var domify = require('domify');
var each = require('each');
var Emitter = require('emitter');
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Add a new option to the integration by `key` with default `value`.
*
* @param {String} key
* @param {Mixed} value
* @return {Integration}
*/
exports.option = function(key, value){
this.prototype.defaults[key] = value;
return this;
};
/**
* Add a new mapping option.
*
* This will create a method `name` that will return a mapping
* for you to use.
*
* Example:
*
* Integration('My Integration')
* .mapping('events');
*
* new MyIntegration().track('My Event');
*
* .track = function(track){
* var events = this.events(track.event());
* each(events, send);
* };
*
* @param {String} name
* @return {Integration}
*/
exports.mapping = function(name){
this.option(name, []);
this.prototype[name] = function(str){
return this.map(this.options[name], str);
};
return this;
};
/**
* Register a new global variable `key` owned by the integration, which will be
* used to test whether the integration is already on the page.
*
* @param {String} global
* @return {Integration}
*/
exports.global = function(key){
this.prototype.globals.push(key);
return this;
};
/**
* Mark the integration as assuming an initial pageview, so to defer loading
* the script until the first `page` call, noop the first `initialize`.
*
* @return {Integration}
*/
exports.assumesPageview = function(){
this.prototype._assumesPageview = true;
return this;
};
/**
* Mark the integration as being "ready" once `load` is called.
*
* @return {Integration}
*/
exports.readyOnLoad = function(){
this.prototype._readyOnLoad = true;
return this;
};
/**
* Mark the integration as being "ready" once `initialize` is called.
*
* @return {Integration}
*/
exports.readyOnInitialize = function(){
this.prototype._readyOnInitialize = true;
return this;
};
/**
* Define a tag to be loaded.
*
* @param {String} str DOM tag as string or URL
* @return {Integration}
*/
exports.tag = function(name, str){
if (null == str) {
str = name;
name = 'library';
}
this.prototype.templates[name] = objectify(str);
return this;
};
/**
* Given a string, give back DOM attributes.
*
* Do it in a way where the browser doesn't load images or iframes.
* It turns out, domify will load images/iframes, because
* whenever you construct those DOM elements,
* the browser immediately loads them.
*
* @param {String} str
* @return {Object}
*/
function objectify(str) {
// replace `src` with `data-src` to prevent image loading
str = str.replace(' src="', ' data-src="');
var el = domify(str);
var attrs = {};
each(el.attributes, function(attr){
// then replace it back
var name = 'data-src' == attr.name ? 'src' : attr.name;
if (!~str.indexOf(attr.name + '=')) return;
attrs[name] = attr.value;
});
return {
type: el.tagName.toLowerCase(),
attrs: attrs
};
}
}, {"after":111,"domify":119,"each":112,"emitter":110}],
119: [function(require, module, exports) {
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Tests for browser support.
*/
var div = document.createElement('div');
// Setup
div.innerHTML = ' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
var innerHTMLBug = !div.getElementsByTagName('link').length;
div = undefined;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
// for script/link/style tags to work in IE6-8, you have to wrap
// in a div with a non-whitespace character in front, ha!
_default: innerHTMLBug ? [1, 'X<div>', '</div>'] : [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.polyline =
map.ellipse =
map.polygon =
map.circle =
map.text =
map.line =
map.path =
map.rect =
map.g = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return a DOM Node instance, which could be a TextNode,
* HTML DOM Node of some kind (<div> for example), or a DocumentFragment
* instance, depending on the contents of the `html` string.
*
* @param {String} html - HTML string to "domify"
* @param {Document} doc - The `document` instance to create the Node for
* @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance
* @api private
*/
function parse(html, doc) {
if ('string' != typeof html) throw new TypeError('String expected');
// default to the global `document` object
if (!doc) doc = document;
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return doc.createTextNode(html);
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
var tag = m[1];
// body support
if (tag == 'body') {
var el = doc.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = doc.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = doc.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
}
}, {}],
89: [function(require, module, exports) {
var toSpace = require('to-space-case');
/**
* Expose `toSnakeCase`.
*/
module.exports = toSnakeCase;
/**
* Convert a `string` to snake case.
*
* @param {String} string
* @return {String}
*/
function toSnakeCase (string) {
return toSpace(string).replace(/\s/g, '_');
}
}, {"to-space-case":120}],
120: [function(require, module, exports) {
var clean = require('to-no-case');
/**
* Expose `toSpaceCase`.
*/
module.exports = toSpaceCase;
/**
* Convert a `string` to space case.
*
* @param {String} string
* @return {String}
*/
function toSpaceCase (string) {
return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) {
return match ? ' ' + match : '';
});
}
}, {"to-no-case":121}],
121: [function(require, module, exports) {
/**
* Expose `toNoCase`.
*/
module.exports = toNoCase;
/**
* Test whether a string is camel-case.
*/
var hasSpace = /\s/;
var hasCamel = /[a-z][A-Z]/;
var hasSeparator = /[\W_]/;
/**
* Remove any starting case from a `string`, like camel or snake, but keep
* spaces and punctuation that may be important otherwise.
*
* @param {String} string
* @return {String}
*/
function toNoCase (string) {
if (hasSpace.test(string)) return string.toLowerCase();
if (hasSeparator.test(string)) string = unseparate(string);
if (hasCamel.test(string)) string = uncamelize(string);
return string.toLowerCase();
}
/**
* Separator splitter.
*/
var separatorSplitter = /[\W_]+(.|$)/g;
/**
* Un-separate a `string`.
*
* @param {String} string
* @return {String}
*/
function unseparate (string) {
return string.replace(separatorSplitter, function (m, next) {
return next ? ' ' + next : '';
});
}
/**
* Camelcase splitter.
*/
var camelSplitter = /(.)([A-Z]+)/g;
/**
* Un-camelcase a `string`.
*
* @param {String} string
* @return {String}
*/
function uncamelize (string) {
return string.replace(camelSplitter, function (m, previous, uppers) {
return previous + ' ' + uppers.toLowerCase().split('').join(' ');
});
}
}, {}],
90: [function(require, module, exports) {
/**
* Protocol.
*/
module.exports = function (url) {
switch (arguments.length) {
case 0: return check();
case 1: return transform(url);
}
};
/**
* Transform a protocol-relative `url` to the use the proper protocol.
*
* @param {String} url
* @return {String}
*/
function transform (url) {
return check() ? 'https:' + url : 'http:' + url;
}
/**
* Check whether `https:` be used for loading scripts.
*
* @return {Boolean}
*/
function check () {
return (
location.protocol == 'https:' ||
location.protocol == 'chrome-extension:'
);
}
}, {}],
91: [function(require, module, exports) {
var isEmpty = require('is-empty');
try {
var typeOf = require('type');
} catch (e) {
var typeOf = require('component-type');
}
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
}, {"is-empty":122,"type":7,"component-type":7}],
122: [function(require, module, exports) {
/**
* Expose `isEmpty`.
*/
module.exports = isEmpty;
/**
* Has.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Test whether a value is "empty".
*
* @param {Mixed} val
* @return {Boolean}
*/
function isEmpty (val) {
if (null == val) return true;
if ('number' == typeof val) return 0 === val;
if (undefined !== val.length) return 0 === val.length;
for (var key in val) if (has.call(val, key)) return false;
return true;
}
}, {}],
92: [function(require, module, exports) {
var identity = function(_){ return _; };
/**
* Module exports, export
*/
module.exports = multiple(find);
module.exports.find = module.exports;
/**
* Export the replacement function, return the modified object
*/
module.exports.replace = function (obj, key, val, options) {
multiple(replace).call(this, obj, key, val, options);
return obj;
};
/**
* Export the delete function, return the modified object
*/
module.exports.del = function (obj, key, options) {
multiple(del).call(this, obj, key, null, options);
return obj;
};
/**
* Compose applying the function to a nested key
*/
function multiple (fn) {
return function (obj, path, val, options) {
var normalize = options && isFunction(options.normalizer) ? options.normalizer : defaultNormalize;
path = normalize(path);
var key;
var finished = false;
while (!finished) loop();
function loop() {
for (key in obj) {
var normalizedKey = normalize(key);
if (0 === path.indexOf(normalizedKey)) {
var temp = path.substr(normalizedKey.length);
if (temp.charAt(0) === '.' || temp.length === 0) {
path = temp.substr(1);
var child = obj[key];
// we're at the end and there is nothing.
if (null == child) {
finished = true;
return;
}
// we're at the end and there is something.
if (!path.length) {
finished = true;
return;
}
// step into child
obj = child;
// but we're done here
return;
}
}
}
key = undefined;
// if we found no matching properties
// on the current object, there's no match.
finished = true;
}
if (!key) return;
if (null == obj) return obj;
// the `obj` and `key` is one above the leaf object and key, so
// start object: { a: { 'b.c': 10 } }
// end object: { 'b.c': 10 }
// end key: 'b.c'
// this way, you can do `obj[key]` and get `10`.
return fn(obj, key, val);
};
}
/**
* Find an object by its key
*
* find({ first_name : 'Calvin' }, 'firstName')
*/
function find (obj, key) {
if (obj.hasOwnProperty(key)) return obj[key];
}
/**
* Delete a value for a given key
*
* del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' }
*/
function del (obj, key) {
if (obj.hasOwnProperty(key)) delete obj[key];
return obj;
}
/**
* Replace an objects existing value with a new one
*
* replace({ a : 'b' }, 'a', 'c') -> { a : 'c' }
*/
function replace (obj, key, val) {
if (obj.hasOwnProperty(key)) obj[key] = val;
return obj;
}
/**
* Normalize a `dot.separated.path`.
*
* A.HELL(!*&#(!)O_WOR LD.bar => ahelloworldbar
*
* @param {String} path
* @return {String}
*/
function defaultNormalize(path) {
return path.replace(/[^a-zA-Z0-9\.]+/g, '').toLowerCase();
}
/**
* Check if a value is a function.
*
* @param {*} val
* @return {boolean} Returns `true` if `val` is a function, otherwise `false`.
*/
function isFunction(val) {
return typeof val === 'function';
}
}, {}],
9: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var domify = require('domify');
var each = require('each');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `AdWords`.
*/
var AdWords = module.exports = integration('AdWords')
.option('conversionId', '')
.option('remarketing', false)
.tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">')
.mapping('events');
/**
* Load.
*
* @param {Function} fn
* @api public
*/
AdWords.prototype.initialize = function(){
this.load(this.ready);
};
/**
* Loaded.
*
* @return {Boolean}
* @api public
*/
AdWords.prototype.loaded = function(){
return !! document.body;
};
/**
* Page.
*
* https://support.google.com/adwords/answer/3111920#standard_parameters
* https://support.google.com/adwords/answer/3103357
* https://developers.google.com/adwords-remarketing-tag/asynchronous/
* https://developers.google.com/adwords-remarketing-tag/parameters
*
* @param {Page} page
*/
AdWords.prototype.page = function(page){
var remarketing = !!this.options.remarketing;
var id = this.options.conversionId;
var props = {};
window.google_trackConversion({
google_conversion_id: id,
google_custom_params: props,
google_remarketing_only: remarketing
});
};
/**
* Track.
*
* @param {Track}
* @api public
*/
AdWords.prototype.track = function(track){
var id = this.options.conversionId;
var events = this.events(track.event());
var revenue = track.revenue() || 0;
each(events, function(label){
var props = track.properties();
delete props.revenue
window.google_trackConversion({
google_conversion_id: id,
google_custom_params: props,
google_conversion_language: 'en',
google_conversion_format: '3',
google_conversion_color: 'ffffff',
google_conversion_label: label,
google_conversion_value: revenue,
google_remarketing_only: false
});
});
};
}, {"analytics.js-integration":88,"domify":119,"each":4}],
10: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
/**
* Expose Alexa integration.
*/
var Alexa = module.exports = integration('Alexa')
.assumesPageview()
.global('_atrk_opts')
.option('account', null)
.option('domain', '')
.option('dynamic', true)
.tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Alexa.prototype.initialize = function(page){
var self = this;
window._atrk_opts = {
atrk_acct: this.options.account,
domain: this.options.domain,
dynamic: this.options.dynamic
};
this.load(function(){
window.atrk();
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Alexa.prototype.loaded = function(){
return !! window.atrk;
};
}, {"analytics.js-integration":88}],
11: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var utm = require('utm-params');
var top = require('top-domain');
/**
* UMD ?
*/
var umd = 'function' == typeof define && define.amd;
/**
* Source.
*/
var src = '//d24n15hnbwhuhn.cloudfront.net/libs/amplitude-2.1.0-min.js';
/**
* Expose `Amplitude` integration.
*/
var Amplitude = module.exports = integration('Amplitude')
.global('amplitude')
.option('apiKey', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('trackUtmProperties', true)
.tag('<script src="' + src + '">');
/**
* Initialize.
*
* https://github.com/amplitude/Amplitude-Javascript
*
* @param {Object} page
*/
Amplitude.prototype.initialize = function(page){
// jscs:disable
(function(e,t){var r=e.amplitude||{};r._q=[];function a(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var i=["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];for(var o=0;o<i.length;o++){a(i[o])}e.amplitude=r})(window,document);
// jscs:enable
this.setDomain(window.location.href);
window.amplitude.init(this.options.apiKey, null, {
includeUtm: this.options.trackUtmProperties
});
var self = this;
if (umd) {
window.require([src], function(amplitude){
window.amplitude = amplitude;
self.ready();
});
return;
}
this.load(function(){
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Amplitude.prototype.loaded = function(){
return !! (window.amplitude && window.amplitude.options);
};
/**
* Page.
*
* @param {Page} page
*/
Amplitude.prototype.page = function(page){
var properties = page.properties();
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Identify.
*
* @param {Facade} identify
*/
Amplitude.prototype.identify = function(identify){
var id = identify.userId();
var traits = identify.traits();
if (id) window.amplitude.setUserId(id);
if (traits) window.amplitude.setUserProperties(traits);
};
/**
* Track.
*
* @param {Track} event
*/
Amplitude.prototype.track = function(track){
var props = track.properties();
var event = track.event();
var revenue = track.revenue();
// track the event
window.amplitude.logEvent(event, props);
// also track revenue
if (revenue) {
window.amplitude.logRevenue(revenue, props.quantity, props.productId);
}
};
/**
* Set domain name to root domain
*
* @param {String} href
*/
Amplitude.prototype.setDomain = function(href){
var domain = top(href);
window.amplitude.setDomain(domain);
};
/**
* Override device ID
*
* @param {String} deviceId
*/
Amplitude.prototype.setDeviceId = function(deviceId){
if (deviceId) window.amplitude.setDeviceId(deviceId);
};
}, {"analytics.js-integration":88,"utm-params":123,"top-domain":124}],
123: [function(require, module, exports) {
/**
* Module dependencies.
*/
var parse = require('querystring').parse;
/**
* Expose `utm`
*/
module.exports = utm;
/**
* Get all utm params from the given `querystring`
*
* @param {String} query
* @return {Object}
* @api private
*/
function utm(query){
if ('?' == query.charAt(0)) query = query.substring(1);
var query = query.replace(/\?/g, '&');
var params = parse(query);
var param;
var ret = {};
for (var key in params) {
if (~key.indexOf('utm_')) {
param = key.substr(4);
if ('campaign' == param) param = 'name';
ret[param] = params[key];
}
}
return ret;
}
}, {"querystring":125}],
125: [function(require, module, exports) {
/**
* Module dependencies.
*/
var encode = encodeURIComponent;
var decode = decodeURIComponent;
var trim = require('trim');
var type = require('type');
var pattern = /(\w+)\[(\d+)\]/
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
if ('?' == str.charAt(0)) str = str.slice(1);
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
var key = decode(parts[0]);
var m;
if (m = pattern.exec(key)) {
obj[m[1]] = obj[m[1]] || [];
obj[m[1]][m[2]] = decode(parts[1]);
continue;
}
obj[parts[0]] = null == parts[1]
? ''
: decode(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
var value = obj[key];
if ('array' == type(value)) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
}
continue;
}
pairs.push(encode(key) + '=' + encode(obj[key]));
}
return pairs.join('&');
};
}, {"trim":126,"type":7}],
126: [function(require, module, exports) {
exports = module.exports = trim;
function trim(str){
if (str.trim) return str.trim();
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
if (str.trimLeft) return str.trimLeft();
return str.replace(/^\s*/, '');
};
exports.right = function(str){
if (str.trimRight) return str.trimRight();
return str.replace(/\s*$/, '');
};
}, {}],
124: [function(require, module, exports) {
/**
* Module dependencies.
*/
var parse = require('url').parse;
/**
* Expose `domain`
*/
module.exports = domain;
/**
* RegExp
*/
var regexp = /[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;
/**
* Get the top domain.
*
* Official Grammar: http://tools.ietf.org/html/rfc883#page-56
* Look for tlds with up to 2-6 characters.
*
* Example:
*
* domain('http://localhost:3000/baz');
* // => ''
* domain('http://dev:3000/baz');
* // => ''
* domain('http://127.0.0.1:3000/baz');
* // => ''
* domain('http://segment.io/baz');
* // => 'segment.io'
*
* @param {String} url
* @return {String}
* @api public
*/
function domain(url){
var host = parse(url).hostname;
var match = host.match(regexp);
return match ? match[0] : '';
};
}, {"url":127}],
127: [function(require, module, exports) {
/**
* Parse the given `url`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(url){
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host || location.host,
port: ('0' === a.port || '' === a.port) ? port(a.protocol) : a.port,
hash: a.hash,
hostname: a.hostname || location.hostname,
pathname: a.pathname.charAt(0) != '/' ? '/' + a.pathname : a.pathname,
protocol: !a.protocol || ':' == a.protocol ? location.protocol : a.protocol,
search: a.search,
query: a.search.slice(1)
};
};
/**
* Check if `url` is absolute.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isAbsolute = function(url){
return 0 == url.indexOf('//') || !!~url.indexOf('://');
};
/**
* Check if `url` is relative.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isRelative = function(url){
return !exports.isAbsolute(url);
};
/**
* Check if `url` is cross domain.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isCrossDomain = function(url){
url = exports.parse(url);
var location = exports.parse(window.location.href);
return url.hostname !== location.hostname
|| url.port !== location.port
|| url.protocol !== location.protocol;
};
/**
* Return default port for `protocol`.
*
* @param {String} protocol
* @return {String}
* @api private
*/
function port (protocol){
switch (protocol) {
case 'http:':
return 80;
case 'https:':
return 443;
default:
return location.port;
}
}
}, {}],
12: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var load = require('load-script');
var is = require('is');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Appcues);
};
/**
* Expose `Appcues` integration.
*/
var Appcues = exports.Integration = integration('Appcues')
.assumesPageview()
.global('Appcues')
.option('appcuesId', '');
/**
* Initialize.
*
* http://appcues.com/docs/
*
* @param {Object}
*/
Appcues.prototype.initialize = function(){
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Appcues.prototype.loaded = function(){
return is.object(window.Appcues);
};
/**
* Load the Appcues library.
*
* @param {Function} callback
*/
Appcues.prototype.load = function(callback){
var id = this.options.appcuesId || 'appcues';
var script = load('//fast.appcues.com/' + id + '.js', callback);
};
/**
* Identify.
*
* http://appcues.com/docs#identify
*
* @param {Identify} identify
*/
Appcues.prototype.identify = function(identify){
window.Appcues.identify(identify.userId(), identify.traits());
};
}, {"analytics.js-integration":88,"load-script":128,"is":91}],
128: [function(require, module, exports) {
/**
* Module dependencies.
*/
var onload = require('script-onload');
var tick = require('next-tick');
var type = require('type');
/**
* Expose `loadScript`.
*
* @param {Object} options
* @param {Function} fn
* @api public
*/
module.exports = function loadScript(options, fn){
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if ('string' == type(options)) options = { src : options };
var https = document.location.protocol === 'https:' ||
document.location.protocol === 'chrome-extension:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = https ? 'https:' + options.src : 'http:' + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) options.src = options.https;
else if (!https && options.http) options.src = options.http;
// Make the `<script>` element and insert it before the first script on the
// page, which is guaranteed to exist since this Javascript is running.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = options.src;
// If we have a fn, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if ('function' == type(fn)) {
onload(script, fn);
}
tick(function(){
// Append after event listeners are attached for IE.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
});
// Return the script element in case they want to do anything special, like
// give it an ID or attributes.
return script;
};
}, {"script-onload":115,"next-tick":103,"type":7}],
13: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var is = require('is');
/**
* Expose `Atatus` integration.
*/
var Atatus = module.exports = integration('Atatus')
.global('atatus')
.option('apiKey', '')
.tag('<script src="//www.atatus.com/atatus.js">');
/**
* Initialize.
*
* https://www.atatus.com/docs.html
*
* @param {Object} page
*/
Atatus.prototype.initialize = function(page){
var self = this;
this.load(function(){
// Configure Atatus and install default handler to capture uncaught exceptions
window.atatus.config(self.options.apiKey).install();
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Atatus.prototype.loaded = function(){
return is.object(window.atatus);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Atatus.prototype.identify = function(identify){
window.atatus.setCustomData({ person: identify.traits() });
};
}, {"analytics.js-integration":88,"is":91}],
14: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
/**
* Expose `Autosend` integration.
*/
var Autosend = module.exports = integration('Autosend')
.global('_autosend')
.option('appKey', '')
.tag('<script id="asnd-tracker" src="https://d2zjxodm1cz8d6.cloudfront.net/js/v1/autosend.js" data-auth-key="{{ appKey }}">');
/**
* Initialize.
*
* http://autosend.io/faq/install-autosend-using-javascript/
*
* @param {Object} page
*/
Autosend.prototype.initialize = function(page){
window._autosend = window._autosend || [];
(function(){var a,b,c;a=function(f){return function(){window._autosend.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b=["identify", "track", "cb"];for (c=0;c<b.length;c++){window._autosend[b[c]]=a(b[c]); } })();
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Autosend.prototype.loaded = function(){
return !! (window._autosend);
};
/**
* Identify.
*
* http://autosend.io/faq/install-autosend-using-javascript/
*
* @param {Identify} identify
*/
Autosend.prototype.identify = function(identify){
var id = identify.userId();
if (!id) return;
var traits = identify.traits();
traits.id = id;
window._autosend.identify(traits);
};
/**
* Track.
*
* http://autosend.io/faq/install-autosend-using-javascript/
*
* @param {Track} track
*/
Autosend.prototype.track = function(track){
window._autosend.track(track.event());
};
}, {"analytics.js-integration":88}],
15: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var each = require('each');
/**
* Expose `Awesm` integration.
*/
var Awesm = module.exports = integration('awe.sm')
.assumesPageview()
.global('AWESM')
.option('apiKey', '')
.tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">')
.mapping('events');
/**
* Initialize.
*
* http://developers.awe.sm/guides/javascript/
*
* @param {Object} page
*/
Awesm.prototype.initialize = function(page){
window.AWESM = { api_key: this.options.apiKey };
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesm.prototype.loaded = function(){
return !! (window.AWESM && window.AWESM._exists);
};
/**
* Track.
*
* @param {Track} track
*/
Awesm.prototype.track = function(track){
var user = this.analytics.user();
var goals = this.events(track.event());
each(goals, function(goal){
window.AWESM.convert(goal, track.cents(), null, user.id());
});
};
}, {"analytics.js-integration":88,"each":4}],
16: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var onbody = require('on-body');
var domify = require('domify');
var extend = require('extend');
var bind = require('bind');
var when = require('when');
var each = require('each');
/**
* HOP.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Noop.
*/
var noop = function(){};
/**
* Expose `Bing`.
*
* https://bingads.microsoft.com/campaign/signup
*/
var Bing = module.exports = integration('Bing Ads')
.global('uetq')
.option('tagId', '')
.tag('<script src="//bat.bing.com/bat.js">');
/**
* Initialize
*
* inferred from their snippet
* https://gist.github.com/sperand-io/8bef4207e9c66e1aa83b
*/
Bing.prototype.initialize = function(){
window.uetq = window.uetq || [];
var self = this;
self.load(function(){
var setup = {
ti: self.options.tagId,
q: window.uetq
};
window.uetq = new UET(setup);
self.ready();
});
};
/**
* Loaded?
*
* Check for custom `push` method bestowed by UET constructor
*
* @return {Boolean}
*/
Bing.prototype.loaded = function(){
return !! (window.uetq && window.uetq.push !== Array.prototype.push);
};
/**
* Page
*/
Bing.prototype.page = function(){
window.uetq.push("pageLoad");
};
/**
* Track
*
* Send all events then set goals based
* on them retroactively: http://advertise.bingads.microsoft.com/en-us/uahelp-topic?market=en&project=Bing_Ads&querytype=topic&query=HLP_BA_PROC_UET.htm
*
* @param {Track} track
*/
Bing.prototype.track = function(track){
var event = {
ea: 'track',
el: track.event()
};
if (track.category()) event.ec = track.category();
if (track.revenue()) event.ev = track.revenue();
window.uetq.push(event);
};
}, {"analytics.js-integration":88,"on-body":129,"domify":119,"extend":130,"bind":101,"when":131,"each":4}],
129: [function(require, module, exports) {
var each = require('each');
/**
* Cache whether `<body>` exists.
*/
var body = false;
/**
* Callbacks to call when the body exists.
*/
var callbacks = [];
/**
* Export a way to add handlers to be invoked once the body exists.
*
* @param {Function} callback A function to call when the body exists.
*/
module.exports = function onBody (callback) {
if (body) {
call(callback);
} else {
callbacks.push(callback);
}
};
/**
* Set an interval to check for `document.body`.
*/
var interval = setInterval(function () {
if (!document.body) return;
body = true;
each(callbacks, call);
clearInterval(interval);
}, 5);
/**
* Call a callback, passing it the body.
*
* @param {Function} callback The callback to call.
*/
function call (callback) {
callback(document.body);
}
}, {"each":112}],
130: [function(require, module, exports) {
module.exports = function extend (object) {
// Takes an unlimited number of extenders.
var args = Array.prototype.slice.call(arguments, 1);
// For each extender, copy their properties on our object.
for (var i = 0, source; source = args[i]; i++) {
if (!source) continue;
for (var property in source) {
object[property] = source[property];
}
}
return object;
};
}, {}],
131: [function(require, module, exports) {
var callback = require('callback');
/**
* Expose `when`.
*/
module.exports = when;
/**
* Loop on a short interval until `condition()` is true, then call `fn`.
*
* @param {Function} condition
* @param {Function} fn
* @param {Number} interval (optional)
*/
function when (condition, fn, interval) {
if (condition()) return callback.async(fn);
var ref = setInterval(function () {
if (!condition()) return;
callback(fn);
clearInterval(ref);
}, interval || 10);
}
}, {"callback":94}],
17: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
/**
* Expose `Blueshift` integration.
*/
var Blueshift = module.exports = integration('Blueshift')
.global('blueshift')
.global('_blueshiftid')
.option('apiKey', '')
.option('retarget', false)
.tag('<script src="https://cdn.getblueshift.com/blueshift.js">');
/**
* Initialize.
*
* Documentation: http://getblueshift.com/documentation
*
* @param {Object} page
*/
Blueshift.prototype.initialize = function(page){
window.blueshift=window.blueshift||[];
// jscs:disable
window.blueshift.load=function(a){window._blueshiftid=a;var d=function(a){return function(){blueshift.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track","click", "pageload", "capture", "retarget"];for(var f=0;f<e.length;f++)blueshift[e[f]]=d(e[f])};
// jscs:enable
window.blueshift.load(this.options.apiKey);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Blueshift.prototype.loaded = function(){
return !! (window.blueshift && window._blueshiftid);
};
/**
* Page.
*
* @param {Page} page
*/
Blueshift.prototype.page = function(page){
if (this.options.retarget) window.blueshift.retarget();
var properties = page.properties();
properties._bsft_source = 'segment.com';
window.blueshift.pageload(properties);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Blueshift.prototype.identify = function(identify){
if (!identify.userId()) return this.debug('user id required');
var traits = identify.traits({ created: 'created_at' });
traits._bsft_source = 'segment.com';
window.blueshift.identify(traits);
};
/**
* Group.
*
* @param {Group} group
*/
Blueshift.prototype.group = function(group){
var traits = group.traits({ created: 'created_at' });
traits._bsft_source = 'segment.com';
window.blueshift.track('group', traits);
};
/**
* Track.
*
* @param {Track} track
*/
Blueshift.prototype.track = function(track){
var properties = track.properties();
properties._bsft_source = 'segment.com';
window.blueshift.track(track.event(), properties);
};
}, {"analytics.js-integration":88}],
18: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var Identify = require('facade').Identify;
var Track = require('facade').Track;
var pixel = require('load-pixel')('http://app.bronto.com/public/');
var qs = require('querystring');
var each = require('each');
/**
* Expose `Bronto` integration.
*/
var Bronto = module.exports = integration('Bronto')
.global('__bta')
.option('siteId', '')
.option('host', '')
.tag('<script src="//p.bm23.com/bta.js">');
/**
* Initialize.
*
* http://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_data_store_js#addingjavascriptconversiontrackingtoyoursite
* http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB
* http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB
*
* @param {Object} page
*/
Bronto.prototype.initialize = function(page){
var self = this;
var params = qs.parse(window.location.search);
if (!params._bta_tid && !params._bta_c) {
this.debug('missing tracking URL parameters `_bta_tid` and `_bta_c`.');
}
this.load(function(){
var opts = self.options;
self.bta = new window.__bta(opts.siteId);
if (opts.host) self.bta.setHost(opts.host);
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bronto.prototype.loaded = function(){
return this.bta;
};
/**
* Completed order.
*
* The cookie is used to link the order being processed back to the delivery,
* message, and contact which makes it a conversion.
* Passing in just the email ensures that the order itself
* gets linked to the contact record in Bronto even if the user
* does not have a tracking cookie.
*
* @param {Track} track
* @api private
*/
Bronto.prototype.completedOrder = function(track){
var user = this.analytics.user();
var products = track.products();
var props = track.properties();
var items = [];
var identify = new Identify({
userId: user.id(),
traits: user.traits()
});
var email = identify.email();
// items
each(products, function(product){
var track = new Track({ properties: product });
items.push({
item_id: track.id() || track.sku(),
desc: product.description || track.name(),
quantity: track.quantity(),
amount: track.price(),
});
});
// add conversion
this.bta.addOrder({
order_id: track.orderId(),
email: email,
// they recommend not putting in a date
// because it needs to be formatted correctly
// YYYY-MM-DDTHH:MM:SS
items: items
});
};
}, {"analytics.js-integration":88,"facade":132,"load-pixel":133,"querystring":134,"each":4}],
132: [function(require, module, exports) {
var Facade = require('./facade');
/**
* Expose `Facade` facade.
*/
module.exports = Facade;
/**
* Expose specific-method facades.
*/
Facade.Alias = require('./alias');
Facade.Group = require('./group');
Facade.Identify = require('./identify');
Facade.Track = require('./track');
Facade.Page = require('./page');
Facade.Screen = require('./screen');
}, {"./facade":135,"./alias":136,"./group":137,"./identify":138,"./track":139,"./page":140,"./screen":141}],
135: [function(require, module, exports) {
var traverse = require('isodate-traverse');
var isEnabled = require('./is-enabled');
var clone = require('./utils').clone;
var type = require('./utils').type;
var address = require('./address');
var objCase = require('obj-case');
var newDate = require('new-date');
/**
* Expose `Facade`.
*/
module.exports = Facade;
/**
* Initialize a new `Facade` with an `obj` of arguments.
*
* @param {Object} obj
*/
function Facade (obj) {
if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date();
else obj.timestamp = newDate(obj.timestamp);
traverse(obj);
this.obj = obj;
}
/**
* Mixin address traits.
*/
address(Facade.prototype);
/**
* Return a proxy function for a `field` that will attempt to first use methods,
* and fallback to accessing the underlying object directly. You can specify
* deeply nested fields too like:
*
* this.proxy('options.Librato');
*
* @param {String} field
*/
Facade.prototype.proxy = function (field) {
var fields = field.split('.');
field = fields.shift();
// Call a function at the beginning to take advantage of facaded fields
var obj = this[field] || this.field(field);
if (!obj) return obj;
if (typeof obj === 'function') obj = obj.call(this) || {};
if (fields.length === 0) return transform(obj);
obj = objCase(obj, fields.join('.'));
return transform(obj);
};
/**
* Directly access a specific `field` from the underlying object, returning a
* clone so outsiders don't mess with stuff.
*
* @param {String} field
* @return {Mixed}
*/
Facade.prototype.field = function (field) {
var obj = this.obj[field];
return transform(obj);
};
/**
* Utility method to always proxy a particular `field`. You can specify deeply
* nested fields too like:
*
* Facade.proxy('options.Librato');
*
* @param {String} field
* @return {Function}
*/
Facade.proxy = function (field) {
return function () {
return this.proxy(field);
};
};
/**
* Utility method to directly access a `field`.
*
* @param {String} field
* @return {Function}
*/
Facade.field = function (field) {
return function () {
return this.field(field);
};
};
/**
* Proxy multiple `path`.
*
* @param {String} path
* @return {Array}
*/
Facade.multi = function(path){
return function(){
var multi = this.proxy(path + 's');
if ('array' == type(multi)) return multi;
var one = this.proxy(path);
if (one) one = [clone(one)];
return one || [];
};
};
/**
* Proxy one `path`.
*
* @param {String} path
* @return {Mixed}
*/
Facade.one = function(path){
return function(){
var one = this.proxy(path);
if (one) return one;
var multi = this.proxy(path + 's');
if ('array' == type(multi)) return multi[0];
};
};
/**
* Get the basic json object of this facade.
*
* @return {Object}
*/
Facade.prototype.json = function () {
var ret = clone(this.obj);
if (this.type) ret.type = this.type();
return ret;
};
/**
* Get the options of a call (formerly called "context"). If you pass an
* integration name, it will get the options for that specific integration, or
* undefined if the integration is not enabled.
*
* @param {String} integration (optional)
* @return {Object or Null}
*/
Facade.prototype.context =
Facade.prototype.options = function (integration) {
var options = clone(this.obj.options || this.obj.context) || {};
if (!integration) return clone(options);
if (!this.enabled(integration)) return;
var integrations = this.integrations();
var value = integrations[integration] || objCase(integrations, integration);
if ('boolean' == typeof value) value = {};
return value || {};
};
/**
* Check whether an integration is enabled.
*
* @param {String} integration
* @return {Boolean}
*/
Facade.prototype.enabled = function (integration) {
var allEnabled = this.proxy('options.providers.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('integrations.all');
if (typeof allEnabled !== 'boolean') allEnabled = true;
var enabled = allEnabled && isEnabled(integration);
var options = this.integrations();
// If the integration is explicitly enabled or disabled, use that
// First, check options.providers for backwards compatibility
if (options.providers && options.providers.hasOwnProperty(integration)) {
enabled = options.providers[integration];
}
// Next, check for the integration's existence in 'options' to enable it.
// If the settings are a boolean, use that, otherwise it should be enabled.
if (options.hasOwnProperty(integration)) {
var settings = options[integration];
if (typeof settings === 'boolean') {
enabled = settings;
} else {
enabled = true;
}
}
return enabled ? true : false;
};
/**
* Get all `integration` options.
*
* @param {String} integration
* @return {Object}
* @api private
*/
Facade.prototype.integrations = function(){
return this.obj.integrations
|| this.proxy('options.providers')
|| this.options();
};
/**
* Check whether the user is active.
*
* @return {Boolean}
*/
Facade.prototype.active = function () {
var active = this.proxy('options.active');
if (active === null || active === undefined) active = true;
return active;
};
/**
* Get `sessionId / anonymousId`.
*
* @return {Mixed}
* @api public
*/
Facade.prototype.sessionId =
Facade.prototype.anonymousId = function(){
return this.field('anonymousId')
|| this.field('sessionId');
};
/**
* Get `groupId` from `context.groupId`.
*
* @return {String}
* @api public
*/
Facade.prototype.groupId = Facade.proxy('options.groupId');
/**
* Get the call's "super properties" which are just traits that have been
* passed in as if from an identify call.
*
* @param {Object} aliases
* @return {Object}
*/
Facade.prototype.traits = function (aliases) {
var ret = this.proxy('options.traits') || {};
var id = this.userId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('options.traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Add a convenient way to get the library name and version
*/
Facade.prototype.library = function(){
var library = this.proxy('options.library');
if (!library) return { name: 'unknown', version: null };
if (typeof library === 'string') return { name: library, version: null };
return library;
};
/**
* Setup some basic proxies.
*/
Facade.prototype.userId = Facade.field('userId');
Facade.prototype.channel = Facade.field('channel');
Facade.prototype.timestamp = Facade.field('timestamp');
Facade.prototype.userAgent = Facade.proxy('options.userAgent');
Facade.prototype.ip = Facade.proxy('options.ip');
/**
* Return the cloned and traversed object
*
* @param {Mixed} obj
* @return {Mixed}
*/
function transform(obj){
var cloned = clone(obj);
return cloned;
}
}, {"isodate-traverse":142,"./is-enabled":143,"./utils":144,"./address":145,"obj-case":92,"new-date":146}],
142: [function(require, module, exports) {
var is = require('is');
var isodate = require('isodate');
var each;
try {
each = require('each');
} catch (err) {
each = require('each-component');
}
/**
* Expose `traverse`.
*/
module.exports = traverse;
/**
* Traverse an object or array, and return a clone with all ISO strings parsed
* into Date objects.
*
* @param {Object} obj
* @return {Object}
*/
function traverse (input, strict) {
if (strict === undefined) strict = true;
if (is.object(input)) return object(input, strict);
if (is.array(input)) return array(input, strict);
return input;
}
/**
* Object traverser.
*
* @param {Object} obj
* @param {Boolean} strict
* @return {Object}
*/
function object (obj, strict) {
each(obj, function (key, val) {
if (isodate.is(val, strict)) {
obj[key] = isodate.parse(val);
} else if (is.object(val) || is.array(val)) {
traverse(val, strict);
}
});
return obj;
}
/**
* Array traverser.
*
* @param {Array} arr
* @param {Boolean} strict
* @return {Array}
*/
function array (arr, strict) {
each(arr, function (val, x) {
if (is.object(val)) {
traverse(val, strict);
} else if (isodate.is(val, strict)) {
arr[x] = isodate.parse(val);
}
});
return arr;
}
}, {"is":147,"isodate":148,"each":4}],
147: [function(require, module, exports) {
var isEmpty = require('is-empty');
try {
var typeOf = require('type');
} catch (e) {
var typeOf = require('component-type');
}
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
}, {"is-empty":122,"type":7,"component-type":7}],
148: [function(require, module, exports) {
/**
* Matcher, slightly modified from:
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*/
var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;
/**
* Convert an ISO date string to a date. Fallback to native `Date.parse`.
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*
* @param {String} iso
* @return {Date}
*/
exports.parse = function (iso) {
var numericKeys = [1, 5, 6, 7, 11, 12];
var arr = matcher.exec(iso);
var offset = 0;
// fallback to native parsing
if (!arr) return new Date(iso);
// remove undefined values
for (var i = 0, val; val = numericKeys[i]; i++) {
arr[val] = parseInt(arr[val], 10) || 0;
}
// allow undefined days and months
arr[2] = parseInt(arr[2], 10) || 1;
arr[3] = parseInt(arr[3], 10) || 1;
// month is 0-11
arr[2]--;
// allow abitrary sub-second precision
arr[8] = arr[8]
? (arr[8] + '00').substring(0, 3)
: 0;
// apply timezone if one exists
if (arr[4] == ' ') {
offset = new Date().getTimezoneOffset();
} else if (arr[9] !== 'Z' && arr[10]) {
offset = arr[11] * 60 + arr[12];
if ('+' == arr[10]) offset = 0 - offset;
}
var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]);
return new Date(millis);
};
/**
* Checks whether a `string` is an ISO date string. `strict` mode requires that
* the date string at least have a year, month and date.
*
* @param {String} string
* @param {Boolean} strict
* @return {Boolean}
*/
exports.is = function (string, strict) {
if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false;
return matcher.test(string);
};
}, {}],
143: [function(require, module, exports) {
/**
* A few integrations are disabled by default. They must be explicitly
* enabled by setting options[Provider] = true.
*/
var disabled = {
Salesforce: true
};
/**
* Check whether an integration should be enabled by default.
*
* @param {String} integration
* @return {Boolean}
*/
module.exports = function (integration) {
return ! disabled[integration];
};
}, {}],
144: [function(require, module, exports) {
/**
* TODO: use component symlink, everywhere ?
*/
try {
exports.inherit = require('inherit');
exports.clone = require('clone');
exports.type = require('type');
} catch (e) {
exports.inherit = require('inherit-component');
exports.clone = require('clone-component');
exports.type = require('type-component');
}
}, {"inherit":149,"clone":150,"type":7}],
149: [function(require, module, exports) {
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
}, {}],
150: [function(require, module, exports) {
/**
* Module dependencies.
*/
var type;
try {
type = require('component-type');
} catch (_) {
type = require('type');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
}, {"component-type":7,"type":7}],
145: [function(require, module, exports) {
/**
* Module dependencies.
*/
var get = require('obj-case');
/**
* Add address getters to `proto`.
*
* @param {Function} proto
*/
module.exports = function(proto){
proto.zip = trait('postalCode', 'zip');
proto.country = trait('country');
proto.street = trait('street');
proto.state = trait('state');
proto.city = trait('city');
function trait(a, b){
return function(){
var traits = this.traits();
var props = this.properties ? this.properties() : {};
return get(traits, 'address.' + a)
|| get(traits, a)
|| (b ? get(traits, 'address.' + b) : null)
|| (b ? get(traits, b) : null)
|| get(props, 'address.' + a)
|| get(props, a)
|| (b ? get(props, 'address.' + b) : null)
|| (b ? get(props, b) : null);
};
}
};
}, {"obj-case":92}],
146: [function(require, module, exports) {
var is = require('is');
var isodate = require('isodate');
var milliseconds = require('./milliseconds');
var seconds = require('./seconds');
/**
* Returns a new Javascript Date object, allowing a variety of extra input types
* over the native Date constructor.
*
* @param {Date|String|Number} val
*/
module.exports = function newDate (val) {
if (is.date(val)) return val;
if (is.number(val)) return new Date(toMs(val));
// date strings
if (isodate.is(val)) return isodate.parse(val);
if (milliseconds.is(val)) return milliseconds.parse(val);
if (seconds.is(val)) return seconds.parse(val);
// fallback to Date.parse
return new Date(val);
};
/**
* If the number passed val is seconds from the epoch, turn it into milliseconds.
* Milliseconds would be greater than 31557600000 (December 31, 1970).
*
* @param {Number} num
*/
function toMs (num) {
if (num < 31557600000) return num * 1000;
return num;
}
}, {"is":151,"isodate":148,"./milliseconds":152,"./seconds":153}],
151: [function(require, module, exports) {
var isEmpty = require('is-empty')
, typeOf = require('type');
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
}, {"is-empty":122,"type":7}],
152: [function(require, module, exports) {
/**
* Matcher.
*/
var matcher = /\d{13}/;
/**
* Check whether a string is a millisecond date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a millisecond string to a date.
*
* @param {String} millis
* @return {Date}
*/
exports.parse = function (millis) {
millis = parseInt(millis, 10);
return new Date(millis);
};
}, {}],
153: [function(require, module, exports) {
/**
* Matcher.
*/
var matcher = /\d{10}/;
/**
* Check whether a string is a second date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a second string to a date.
*
* @param {String} seconds
* @return {Date}
*/
exports.parse = function (seconds) {
var millis = parseInt(seconds, 10) * 1000;
return new Date(millis);
};
}, {}],
136: [function(require, module, exports) {
/**
* Module dependencies.
*/
var inherit = require('./utils').inherit;
var Facade = require('./facade');
/**
* Expose `Alias` facade.
*/
module.exports = Alias;
/**
* Initialize a new `Alias` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @property {String} from
* @property {String} to
* @property {Object} options
*/
function Alias (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Alias, Facade);
/**
* Return type of facade.
*
* @return {String}
*/
Alias.prototype.type =
Alias.prototype.action = function () {
return 'alias';
};
/**
* Get `previousId`.
*
* @return {Mixed}
* @api public
*/
Alias.prototype.from =
Alias.prototype.previousId = function(){
return this.field('previousId')
|| this.field('from');
};
/**
* Get `userId`.
*
* @return {String}
* @api public
*/
Alias.prototype.to =
Alias.prototype.userId = function(){
return this.field('userId')
|| this.field('to');
};
}, {"./utils":144,"./facade":135}],
137: [function(require, module, exports) {
/**
* Module dependencies.
*/
var inherit = require('./utils').inherit;
var address = require('./address');
var isEmail = require('is-email');
var newDate = require('new-date');
var Facade = require('./facade');
/**
* Expose `Group` facade.
*/
module.exports = Group;
/**
* Initialize a new `Group` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} groupId
* @param {Object} properties
* @param {Object} options
*/
function Group (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Group, Facade);
/**
* Get the facade's action.
*/
Group.prototype.type =
Group.prototype.action = function () {
return 'group';
};
/**
* Setup some basic proxies.
*/
Group.prototype.groupId = Facade.field('groupId');
/**
* Get created or createdAt.
*
* @return {Date}
*/
Group.prototype.created = function(){
var created = this.proxy('traits.createdAt')
|| this.proxy('traits.created')
|| this.proxy('properties.createdAt')
|| this.proxy('properties.created');
if (created) return newDate(created);
};
/**
* Get the group's email, falling back to the group ID if it's a valid email.
*
* @return {String}
*/
Group.prototype.email = function () {
var email = this.proxy('traits.email');
if (email) return email;
var groupId = this.groupId();
if (isEmail(groupId)) return groupId;
};
/**
* Get the group's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Group.prototype.traits = function (aliases) {
var ret = this.properties();
var id = this.groupId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Special traits.
*/
Group.prototype.name = Facade.proxy('traits.name');
Group.prototype.industry = Facade.proxy('traits.industry');
Group.prototype.employees = Facade.proxy('traits.employees');
/**
* Get traits or properties.
*
* TODO: remove me
*
* @return {Object}
*/
Group.prototype.properties = function(){
return this.field('traits')
|| this.field('properties')
|| {};
};
}, {"./utils":144,"./address":145,"is-email":154,"new-date":146,"./facade":135}],
154: [function(require, module, exports) {
/**
* Expose `isEmail`.
*/
module.exports = isEmail;
/**
* Email address matcher.
*/
var matcher = /.+\@.+\..+/;
/**
* Loosely validate an email address.
*
* @param {String} string
* @return {Boolean}
*/
function isEmail (string) {
return matcher.test(string);
}
}, {}],
138: [function(require, module, exports) {
var address = require('./address');
var Facade = require('./facade');
var isEmail = require('is-email');
var newDate = require('new-date');
var utils = require('./utils');
var get = require('obj-case');
var trim = require('trim');
var inherit = utils.inherit;
var clone = utils.clone;
var type = utils.type;
/**
* Expose `Idenfity` facade.
*/
module.exports = Identify;
/**
* Initialize a new `Identify` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} sessionId
* @param {Object} traits
* @param {Object} options
*/
function Identify (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Identify, Facade);
/**
* Get the facade's action.
*/
Identify.prototype.type =
Identify.prototype.action = function () {
return 'identify';
};
/**
* Get the user's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Identify.prototype.traits = function (aliases) {
var ret = this.field('traits') || {};
var id = this.userId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
if (alias !== aliases[alias]) delete ret[alias];
}
return ret;
};
/**
* Get the user's email, falling back to their user ID if it's a valid email.
*
* @return {String}
*/
Identify.prototype.email = function () {
var email = this.proxy('traits.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the user's created date, optionally looking for `createdAt` since lots of
* people do that instead.
*
* @return {Date or Undefined}
*/
Identify.prototype.created = function () {
var created = this.proxy('traits.created') || this.proxy('traits.createdAt');
if (created) return newDate(created);
};
/**
* Get the company created date.
*
* @return {Date or undefined}
*/
Identify.prototype.companyCreated = function(){
var created = this.proxy('traits.company.created')
|| this.proxy('traits.company.createdAt');
if (created) return newDate(created);
};
/**
* Get the user's name, optionally combining a first and last name if that's all
* that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.name = function () {
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name);
var firstName = this.firstName();
var lastName = this.lastName();
if (firstName && lastName) return trim(firstName + ' ' + lastName);
};
/**
* Get the user's first name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.firstName = function () {
var firstName = this.proxy('traits.firstName');
if (typeof firstName === 'string') return trim(firstName);
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name).split(' ')[0];
};
/**
* Get the user's last name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.lastName = function () {
var lastName = this.proxy('traits.lastName');
if (typeof lastName === 'string') return trim(lastName);
var name = this.proxy('traits.name');
if (typeof name !== 'string') return;
var space = trim(name).indexOf(' ');
if (space === -1) return;
return trim(name.substr(space + 1));
};
/**
* Get the user's unique id.
*
* @return {String or undefined}
*/
Identify.prototype.uid = function(){
return this.userId()
|| this.username()
|| this.email();
};
/**
* Get description.
*
* @return {String}
*/
Identify.prototype.description = function(){
return this.proxy('traits.description')
|| this.proxy('traits.background');
};
/**
* Get the age.
*
* If the age is not explicitly set
* the method will compute it from `.birthday()`
* if possible.
*
* @return {Number}
*/
Identify.prototype.age = function(){
var date = this.birthday();
var age = get(this.traits(), 'age');
if (null != age) return age;
if ('date' != type(date)) return;
var now = new Date;
return now.getFullYear() - date.getFullYear();
};
/**
* Get the avatar.
*
* .photoUrl needed because help-scout
* implementation uses `.avatar || .photoUrl`.
*
* .avatarUrl needed because trakio uses it.
*
* @return {Mixed}
*/
Identify.prototype.avatar = function(){
var traits = this.traits();
return get(traits, 'avatar')
|| get(traits, 'photoUrl')
|| get(traits, 'avatarUrl');
};
/**
* Get the position.
*
* .jobTitle needed because some integrations use it.
*
* @return {Mixed}
*/
Identify.prototype.position = function(){
var traits = this.traits();
return get(traits, 'position') || get(traits, 'jobTitle');
};
/**
* Setup sme basic "special" trait proxies.
*/
Identify.prototype.username = Facade.proxy('traits.username');
Identify.prototype.website = Facade.one('traits.website');
Identify.prototype.websites = Facade.multi('traits.website');
Identify.prototype.phone = Facade.one('traits.phone');
Identify.prototype.phones = Facade.multi('traits.phone');
Identify.prototype.address = Facade.proxy('traits.address');
Identify.prototype.gender = Facade.proxy('traits.gender');
Identify.prototype.birthday = Facade.proxy('traits.birthday');
}, {"./address":145,"./facade":135,"is-email":154,"new-date":146,"./utils":144,"obj-case":92,"trim":126}],
139: [function(require, module, exports) {
var inherit = require('./utils').inherit;
var clone = require('./utils').clone;
var type = require('./utils').type;
var Facade = require('./facade');
var Identify = require('./identify');
var isEmail = require('is-email');
var get = require('obj-case');
/**
* Expose `Track` facade.
*/
module.exports = Track;
/**
* Initialize a new `Track` facade with a `dictionary` of arguments.
*
* @param {object} dictionary
* @property {String} event
* @property {String} userId
* @property {String} sessionId
* @property {Object} properties
* @property {Object} options
*/
function Track (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Track, Facade);
/**
* Return the facade's action.
*
* @return {String}
*/
Track.prototype.type =
Track.prototype.action = function () {
return 'track';
};
/**
* Setup some basic proxies.
*/
Track.prototype.event = Facade.field('event');
Track.prototype.value = Facade.proxy('properties.value');
/**
* Misc
*/
Track.prototype.category = Facade.proxy('properties.category');
/**
* Ecommerce
*/
Track.prototype.id = Facade.proxy('properties.id');
Track.prototype.sku = Facade.proxy('properties.sku');
Track.prototype.tax = Facade.proxy('properties.tax');
Track.prototype.name = Facade.proxy('properties.name');
Track.prototype.price = Facade.proxy('properties.price');
Track.prototype.total = Facade.proxy('properties.total');
Track.prototype.coupon = Facade.proxy('properties.coupon');
Track.prototype.shipping = Facade.proxy('properties.shipping');
Track.prototype.discount = Facade.proxy('properties.discount');
/**
* Description
*/
Track.prototype.description = Facade.proxy('properties.description');
/**
* Plan
*/
Track.prototype.plan = Facade.proxy('properties.plan');
/**
* Order id.
*
* @return {String}
* @api public
*/
Track.prototype.orderId = function(){
return this.proxy('properties.id')
|| this.proxy('properties.orderId');
};
/**
* Get subtotal.
*
* @return {Number}
*/
Track.prototype.subtotal = function(){
var subtotal = get(this.properties(), 'subtotal');
var total = this.total();
var n;
if (subtotal) return subtotal;
if (!total) return 0;
if (n = this.tax()) total -= n;
if (n = this.shipping()) total -= n;
if (n = this.discount()) total += n;
return total;
};
/**
* Get products.
*
* @return {Array}
*/
Track.prototype.products = function(){
var props = this.properties();
var products = get(props, 'products');
return 'array' == type(products)
? products
: [];
};
/**
* Get quantity.
*
* @return {Number}
*/
Track.prototype.quantity = function(){
var props = this.obj.properties || {};
return props.quantity || 1;
};
/**
* Get currency.
*
* @return {String}
*/
Track.prototype.currency = function(){
var props = this.obj.properties || {};
return props.currency || 'USD';
};
/**
* BACKWARDS COMPATIBILITY: should probably re-examine where these come from.
*/
Track.prototype.referrer = Facade.proxy('properties.referrer');
Track.prototype.query = Facade.proxy('options.query');
/**
* Get the call's properties.
*
* @param {Object} aliases
* @return {Object}
*/
Track.prototype.properties = function (aliases) {
var ret = this.field('properties') || {};
aliases = aliases || {};
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('properties.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get the call's username.
*
* @return {String or Undefined}
*/
Track.prototype.username = function () {
return this.proxy('traits.username') ||
this.proxy('properties.username') ||
this.userId() ||
this.sessionId();
};
/**
* Get the call's email, using an the user ID if it's a valid email.
*
* @return {String or Undefined}
*/
Track.prototype.email = function () {
var email = this.proxy('traits.email');
email = email || this.proxy('properties.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the call's revenue, parsing it from a string with an optional leading
* dollar sign.
*
* For products/services that don't have shipping and are not directly taxed,
* they only care about tracking `revenue`. These are things like
* SaaS companies, who sell monthly subscriptions. The subscriptions aren't
* taxed directly, and since it's a digital product, it has no shipping.
*
* The only case where there's a difference between `revenue` and `total`
* (in the context of analytics) is on ecommerce platforms, where they want
* the `revenue` function to actually return the `total` (which includes
* tax and shipping, total = subtotal + tax + shipping). This is probably
* because on their backend they assume tax and shipping has been applied to
* the value, and so can get the revenue on their own.
*
* @return {Number}
*/
Track.prototype.revenue = function () {
var revenue = this.proxy('properties.revenue');
var event = this.event();
// it's always revenue, unless it's called during an order completion.
if (!revenue && event && event.match(/completed ?order/i)) {
revenue = this.proxy('properties.total');
}
return currency(revenue);
};
/**
* Get cents.
*
* @return {Number}
*/
Track.prototype.cents = function(){
var revenue = this.revenue();
return 'number' != typeof revenue
? this.value() || 0
: revenue * 100;
};
/**
* A utility to turn the pieces of a track call into an identify. Used for
* integrations with super properties or rate limits.
*
* TODO: remove me.
*
* @return {Facade}
*/
Track.prototype.identify = function () {
var json = this.json();
json.traits = this.traits();
return new Identify(json);
};
/**
* Get float from currency value.
*
* @param {Mixed} val
* @return {Number}
*/
function currency(val) {
if (!val) return;
if (typeof val === 'number') return val;
if (typeof val !== 'string') return;
val = val.replace(/\$/g, '');
val = parseFloat(val);
if (!isNaN(val)) return val;
}
}, {"./utils":144,"./facade":135,"./identify":138,"is-email":154,"obj-case":92}],
140: [function(require, module, exports) {
var inherit = require('./utils').inherit;
var Facade = require('./facade');
var Track = require('./track');
/**
* Expose `Page` facade
*/
module.exports = Page;
/**
* Initialize new `Page` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Page(dictionary){
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Page, Facade);
/**
* Get the facade's action.
*
* @return {String}
*/
Page.prototype.type =
Page.prototype.action = function(){
return 'page';
};
/**
* Fields
*/
Page.prototype.category = Facade.field('category');
Page.prototype.name = Facade.field('name');
/**
* Proxies.
*/
Page.prototype.title = Facade.proxy('properties.title');
Page.prototype.path = Facade.proxy('properties.path');
Page.prototype.url = Facade.proxy('properties.url');
/**
* Referrer.
*/
Page.prototype.referrer = function(){
return this.proxy('properties.referrer')
|| this.proxy('context.referrer.url');
};
/**
* Get the page properties mixing `category` and `name`.
*
* @return {Object}
*/
Page.prototype.properties = function(){
var props = this.field('properties') || {};
var category = this.category();
var name = this.name();
if (category) props.category = category;
if (name) props.name = name;
return props;
};
/**
* Get the page fullName.
*
* @return {String}
*/
Page.prototype.fullName = function(){
var category = this.category();
var name = this.name();
return name && category
? category + ' ' + name
: name;
};
/**
* Get event with `name`.
*
* @return {String}
*/
Page.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Page'
: 'Loaded a Page';
};
/**
* Convert this Page to a Track facade with `name`.
*
* @param {String} name
* @return {Track}
*/
Page.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
timestamp: this.timestamp(),
context: this.context(),
properties: props
});
};
}, {"./utils":144,"./facade":135,"./track":139}],
141: [function(require, module, exports) {
var inherit = require('./utils').inherit;
var Page = require('./page');
var Track = require('./track');
/**
* Expose `Screen` facade
*/
module.exports = Screen;
/**
* Initialize new `Screen` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Screen(dictionary){
Page.call(this, dictionary);
}
/**
* Inherit from `Page`
*/
inherit(Screen, Page);
/**
* Get the facade's action.
*
* @return {String}
* @api public
*/
Screen.prototype.type =
Screen.prototype.action = function(){
return 'screen';
};
/**
* Get event with `name`.
*
* @param {String} name
* @return {String}
* @api public
*/
Screen.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Screen'
: 'Loaded a Screen';
};
/**
* Convert this Screen.
*
* @param {String} name
* @return {Track}
* @api public
*/
Screen.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
timestamp: this.timestamp(),
context: this.context(),
properties: props
});
};
}, {"./utils":144,"./page":140,"./track":139}],
133: [function(require, module, exports) {
/**
* Module dependencies.
*/
var stringify = require('querystring').stringify;
var sub = require('substitute');
/**
* Factory function to create a pixel loader.
*
* @param {String} path
* @return {Function}
* @api public
*/
module.exports = function(path){
return function(query, obj, fn){
if ('function' == typeof obj) fn = obj, obj = {};
obj = obj || {};
fn = fn || function(){};
var url = sub(path, obj);
var img = new Image;
img.onerror = error(fn, 'failed to load pixel', img);
img.onload = function(){ fn(); };
query = stringify(query);
if (query) query = '?' + query;
img.src = url + query;
img.width = 1;
img.height = 1;
return img;
};
};
/**
* Create an error handler.
*
* @param {Fucntion} fn
* @param {String} message
* @param {Image} img
* @return {Function}
* @api private
*/
function error(fn, message, img){
return function(e){
e = e || window.event;
var err = new Error(message);
err.event = e;
err.source = img;
fn(err);
};
}
}, {"querystring":125,"substitute":155}],
155: [function(require, module, exports) {
/**
* Expose `substitute`
*/
module.exports = substitute;
/**
* Type.
*/
var type = Object.prototype.toString;
/**
* Substitute `:prop` with the given `obj` in `str`
*
* @param {String} str
* @param {Object or Array} obj
* @param {RegExp} expr
* @return {String}
* @api public
*/
function substitute(str, obj, expr){
if (!obj) throw new TypeError('expected an object');
expr = expr || /:(\w+)/g;
return str.replace(expr, function(_, prop){
switch (type.call(obj)) {
case '[object Object]':
return null != obj[prop] ? obj[prop] : _;
case '[object Array]':
var val = obj.shift();
return null != val ? val : _;
}
});
}
}, {}],
134: [function(require, module, exports) {
/**
* Module dependencies.
*/
var encode = encodeURIComponent;
var decode = decodeURIComponent;
var trim = require('trim');
var type = require('type');
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
if ('?' == str.charAt(0)) str = str.slice(1);
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
var key = decode(parts[0]);
var m;
if (m = /(\w+)\[(\d+)\]/.exec(key)) {
obj[m[1]] = obj[m[1]] || [];
obj[m[1]][m[2]] = decode(parts[1]);
continue;
}
obj[parts[0]] = null == parts[1]
? ''
: decode(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
var value = obj[key];
if ('array' == type(value)) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
}
continue;
}
pairs.push(encode(key) + '=' + encode(obj[key]));
}
return pairs.join('&');
};
}, {"trim":126,"type":7}],
19: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var tick = require('next-tick');
/**
* Expose `BugHerd` integration.
*/
var BugHerd = module.exports = integration('BugHerd')
.assumesPageview()
.global('BugHerdConfig')
.global('_bugHerd')
.option('apiKey', '')
.option('showFeedbackTab', true)
.tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');
/**
* Initialize.
*
* http://support.bugherd.com/home
*
* @param {Object} page
*/
BugHerd.prototype.initialize = function(page){
window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }};
var ready = this.ready;
this.load(function(){
tick(ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
BugHerd.prototype.loaded = function(){
return !! window._bugHerd;
};
}, {"analytics.js-integration":88,"next-tick":103}],
20: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var is = require('is');
var extend = require('extend');
var onError = require('on-error');
/**
* UMD ?
*/
var umd = 'function' == typeof define && define.amd;
/**
* Source.
*/
var src = '//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js';
/**
* Expose `Bugsnag` integration.
*/
var Bugsnag = module.exports = integration('Bugsnag')
.global('Bugsnag')
.option('apiKey', '')
.tag('<script src="' + src + '">');
/**
* Initialize.
*
* https://bugsnag.com/docs/notifiers/js
*
* @param {Object} page
*/
Bugsnag.prototype.initialize = function(page){
var self = this;
if (umd) {
window.require([src], function(bugsnag){
bugsnag.apiKey = self.options.apiKey;
window.Bugsnag = bugsnag;
self.ready();
});
return;
}
this.load(function(){
window.Bugsnag.apiKey = self.options.apiKey;
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bugsnag.prototype.loaded = function(){
return is.object(window.Bugsnag);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Bugsnag.prototype.identify = function(identify){
window.Bugsnag.metaData = window.Bugsnag.metaData || {};
extend(window.Bugsnag.metaData, identify.traits());
};
}, {"analytics.js-integration":88,"is":91,"extend":130,"on-error":156}],
156: [function(require, module, exports) {
/**
* Expose `onError`.
*/
module.exports = onError;
/**
* Callbacks.
*/
var callbacks = [];
/**
* Preserve existing handler.
*/
if ('function' == typeof window.onerror) callbacks.push(window.onerror);
/**
* Bind to `window.onerror`.
*/
window.onerror = handler;
/**
* Error handler.
*/
function handler () {
for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments);
}
/**
* Call a `fn` on `window.onerror`.
*
* @param {Function} fn
*/
function onError (fn) {
callbacks.push(fn);
if (window.onerror != handler) {
callbacks.push(window.onerror);
window.onerror = handler;
}
}
}, {}],
21: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var defaults = require('defaults');
var onBody = require('on-body');
/**
* Expose `Chartbeat` integration.
*/
var Chartbeat = module.exports = integration('Chartbeat')
.assumesPageview()
.global('_sf_async_config')
.global('_sf_endpt')
.global('pSUPERFLY')
.option('domain', '')
.option('uid', null)
.tag('<script src="//static.chartbeat.com/js/chartbeat.js">');
/**
* Initialize.
*
* http://chartbeat.com/docs/configuration_variables/
*
* @param {Object} page
*/
Chartbeat.prototype.initialize = function(page){
var self = this;
window._sf_async_config = window._sf_async_config || {};
window._sf_async_config.useCanonical = true;
defaults(window._sf_async_config, this.options);
onBody(function(){
window._sf_endpt = new Date().getTime();
// Note: Chartbeat depends on document.body existing so the script does
// not load until that is confirmed. Otherwise it may trigger errors.
self.load(self.ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Chartbeat.prototype.loaded = function(){
return !! window.pSUPERFLY;
};
/**
* Page.
*
* http://chartbeat.com/docs/handling_virtual_page_changes/
*
* @param {Page} page
*/
Chartbeat.prototype.page = function(page){
var category = page.category();
if (category) window._sf_async_config.sections = category;
var author = page.proxy('properties.author');
if (author) window._sf_async_config.authors = author;
var props = page.properties();
var name = page.fullName();
window.pSUPERFLY.virtualPage(props.path, name || props.title);
};
}, {"analytics.js-integration":88,"defaults":157,"on-body":129}],
157: [function(require, module, exports) {
/**
* Expose `defaults`.
*/
module.exports = defaults;
function defaults (dest, defaults) {
for (var prop in defaults) {
if (! (prop in dest)) {
dest[prop] = defaults[prop];
}
}
return dest;
};
}, {}],
22: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_cbq');
var each = require('each');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Supported events
*/
var supported = {
activation: true,
changePlan: true,
register: true,
refund: true,
charge: true,
cancel: true,
login: true
};
/**
* Expose `ChurnBee` integration.
*/
var ChurnBee = module.exports = integration('ChurnBee')
.global('_cbq')
.global('ChurnBee')
.option('apiKey', '')
.tag('<script src="//api.churnbee.com/cb.js">')
.mapping('events');
/**
* Initialize.
*
* https://churnbee.com/docs
*
* @param {Object} page
*/
ChurnBee.prototype.initialize = function(page){
push('_setApiKey', this.options.apiKey);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
ChurnBee.prototype.loaded = function(){
return !! window.ChurnBee;
};
/**
* Track.
*
* @param {Track} event
*/
ChurnBee.prototype.track = function(track){
var event = track.event();
var events = this.events(event);
events.push(event);
each(events, function(event){
if (true != supported[event]) return;
push(event, track.properties({ revenue: 'amount' }));
});
};
}, {"analytics.js-integration":88,"global-queue":158,"each":4}],
158: [function(require, module, exports) {
/**
* Expose `generate`.
*/
module.exports = generate;
/**
* Generate a global queue pushing method with `name`.
*
* @param {String} name
* @param {Object} options
* @property {Boolean} wrap
* @return {Function}
*/
function generate (name, options) {
options = options || {};
return function (args) {
args = [].slice.call(arguments);
window[name] || (window[name] = []);
options.wrap === false
? window[name].push.apply(window[name], args)
: window[name].push(args);
};
}
}, {}],
23: [function(require, module, exports) {
/**
* Module dependencies.
*/
var date = require('load-date');
var domify = require('domify');
var each = require('each');
var integration = require('analytics.js-integration');
var is = require('is');
var useHttps = require('use-https');
var onBody = require('on-body');
/**
* Expose `ClickTale` integration.
*/
var ClickTale = module.exports = integration('ClickTale')
.assumesPageview()
.global('WRInitTime')
.global('ClickTale')
.global('ClickTaleSetUID')
.global('ClickTaleField')
.global('ClickTaleEvent')
.option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js')
.option('httpsCdnUrl', '')
.option('projectId', '')
.option('recordingRatio', 0.01)
.option('partitionId', '')
.tag('<script src="{{src}}">');
/**
* Initialize.
*
* http://wiki.clicktale.com/Article/JavaScript_API
*
* @param {Object} page
*/
ClickTale.prototype.initialize = function(page){
var self = this;
window.WRInitTime = date.getTime();
onBody(function(body){
body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'));
});
var http = this.options.httpCdnUrl;
var https = this.options.httpsCdnUrl;
if (useHttps() && !https) return this.debug('https option required');
var src = useHttps() ? https : http;
this.load({ src: src }, function(){
window.ClickTale(
self.options.projectId,
self.options.recordingRatio,
self.options.partitionId
);
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
ClickTale.prototype.loaded = function(){
return is.fn(window.ClickTale);
};
/**
* Identify.
*
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField
*
* @param {Identify} identify
*/
ClickTale.prototype.identify = function(identify){
var id = identify.userId();
window.ClickTaleSetUID(id);
each(identify.traits(), function(key, value){
window.ClickTaleField(key, value);
});
};
/**
* Track.
*
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent
*
* @param {Track} track
*/
ClickTale.prototype.track = function(track){
window.ClickTaleEvent(track.event());
};
}, {"load-date":159,"domify":119,"each":4,"analytics.js-integration":88,"is":91,"use-https":90,"on-body":129}],
159: [function(require, module, exports) {
/*
* Load date.
*
* For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/
*/
var time = new Date()
, perf = window.performance;
if (perf && perf.timing && perf.timing.responseEnd) {
time = new Date(perf.timing.responseEnd);
}
module.exports = time;
}, {}],
24: [function(require, module, exports) {
/**
* Module dependencies.
*/
var Identify = require('facade').Identify;
var extend = require('extend');
var integration = require('analytics.js-integration');
var is = require('is');
/**
* Expose `Clicky` integration.
*/
var Clicky = module.exports = integration('Clicky')
.assumesPageview()
.global('clicky')
.global('clicky_site_ids')
.global('clicky_custom')
.option('siteId', null)
.tag('<script src="//static.getclicky.com/js"></script>');
/**
* Initialize.
*
* http://clicky.com/help/customization
*
* @param {Object} page
*/
Clicky.prototype.initialize = function(page){
var user = this.analytics.user();
window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId];
this.identify(new Identify({
userId: user.id(),
traits: user.traits()
}));
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Clicky.prototype.loaded = function(){
return is.object(window.clicky);
};
/**
* Page.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Page} page
*/
Clicky.prototype.page = function(page){
var properties = page.properties();
var category = page.category();
var name = page.fullName();
window.clicky.log(properties.path, name || properties.title);
};
/**
* Identify.
*
* @param {Identify} id (optional)
*/
Clicky.prototype.identify = function(identify){
window.clicky_custom = window.clicky_custom || {};
window.clicky_custom.session = window.clicky_custom.session || {};
var traits = identify.traits();
var username = identify.username();
var email = identify.email();
var name = identify.name();
if (username || email || name) traits.username = username || email || name;
extend(window.clicky_custom.session, traits);
};
/**
* Track.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Track} event
*/
Clicky.prototype.track = function(track){
window.clicky.goal(track.event(), track.revenue());
};
}, {"facade":132,"extend":130,"analytics.js-integration":88,"is":91}],
25: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var useHttps = require('use-https');
/**
* Expose `Comscore` integration.
*/
var Comscore = module.exports = integration('comScore')
.assumesPageview()
.global('_comscore')
.global('COMSCORE')
.option('c1', '2')
.option('c2', '')
.tag('http', '<script src="http://b.scorecardresearch.com/beacon.js">')
.tag('https', '<script src="https://sb.scorecardresearch.com/beacon.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Comscore.prototype.initialize = function(page){
window._comscore = window._comscore || [this.options];
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Comscore.prototype.loaded = function(){
return !! window.COMSCORE;
};
/**
* Page
*
* @param {Object} page
*/
Comscore.prototype.page = function(page){
window.COMSCORE.beacon(this.options);
};
}, {"analytics.js-integration":88,"use-https":90}],
26: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
/**
* Expose `CrazyEgg` integration.
*/
var CrazyEgg = module.exports = integration('Crazy Egg')
.assumesPageview()
.global('CE2')
.option('accountNumber', '')
.tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');
/**
* Initialize.
*
* @param {Object} page
*/
CrazyEgg.prototype.initialize = function(page){
var number = this.options.accountNumber;
var path = number.slice(0,4) + '/' + number.slice(4);
var cache = Math.floor(new Date().getTime() / 3600000);
this.load({ path: path, cache: cache }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
CrazyEgg.prototype.loaded = function(){
return !! window.CE2;
};
}, {"analytics.js-integration":88}],
27: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_curebitq');
var Identify = require('facade').Identify;
var throttle = require('throttle');
var Track = require('facade').Track;
var iso = require('to-iso-string');
var clone = require('clone');
var each = require('each');
var bind = require('bind');
/**
* Expose `Curebit` integration.
*/
var Curebit = module.exports = integration('Curebit')
.global('_curebitq')
.global('curebit')
.option('siteId', '')
.option('iframeWidth', '100%')
.option('iframeHeight', '480')
.option('iframeBorder', 0)
.option('iframeId', 'curebit_integration')
.option('responsive', true)
.option('device', '')
.option('insertIntoId', '')
.option('campaigns', {})
.option('server', 'https://www.curebit.com')
.tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Curebit.prototype.initialize = function(page){
push('init', { site_id: this.options.siteId, server: this.options.server });
this.load(this.ready);
// throttle the call to `page` since curebit needs to append an iframe
this.page = throttle(bind(this, this.page), 250);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Curebit.prototype.loaded = function(){
return !!window.curebit;
};
/**
* Page.
*
* Call the `register_affiliate` method of the Curebit API that will load a
* custom iframe onto the page, only if this page's path is marked as a
* campaign.
*
* http://www.curebit.com/docs/affiliate/registration
*
* This is throttled to prevent accidentally drawing the iframe multiple times,
* from multiple `.page()` calls. The `250` is from the curebit script.
*
* @param {String} url
* @param {String} id
* @param {Function} fn
* @api private
*/
Curebit.prototype.injectIntoId = function(url, id, fn){
var server = this.options.server;
when(function(){
return document.getElementById(id);
}, function(){
var script = document.createElement('script');
script.src = url;
var parent = document.getElementById(id);
parent.appendChild(script);
onload(script, fn);
});
};
/**
* Campaign tags.
*
* @param {Page} page
*/
Curebit.prototype.page = function(page){
var user = this.analytics.user();
var campaigns = this.options.campaigns;
var path = window.location.pathname;
if (!campaigns[path]) return;
var tags = (campaigns[path] || '').split(',');
if (!tags.length) return;
var settings = {
responsive: this.options.responsive,
device: this.options.device,
campaign_tags: tags,
iframe: {
width: this.options.iframeWidth,
height: this.options.iframeHeight,
id: this.options.iframeId,
frameborder: this.options.iframeBorder,
container: this.options.insertIntoId
}
};
var identify = new Identify({
userId: user.id(),
traits: user.traits()
});
// if we have an email, add any information about the user
if (identify.email()) {
settings.affiliate_member = {
email: identify.email(),
first_name: identify.firstName(),
last_name: identify.lastName(),
customer_id: identify.userId()
};
}
push('register_affiliate', settings);
};
/**
* Completed order.
*
* Fire the Curebit `register_purchase` with the order details and items.
*
* https://www.curebit.com/docs/ecommerce/custom
*
* @param {Track} track
*/
Curebit.prototype.completedOrder = function(track){
var user = this.analytics.user();
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
var items = [];
var identify = new Identify({
traits: user.traits(),
userId: user.id()
});
each(products, function(product){
var track = new Track({ properties: product });
items.push({
product_id: track.id() || track.sku(),
quantity: track.quantity(),
image_url: product.image,
price: track.price(),
title: track.name(),
url: product.url,
});
});
push('register_purchase', {
order_date: iso(props.date || new Date()),
order_number: orderId,
coupon_code: track.coupon(),
subtotal: track.total(),
customer_id: identify.userId(),
first_name: identify.firstName(),
last_name: identify.lastName(),
email: identify.email(),
items: items
});
};
}, {"analytics.js-integration":88,"global-queue":158,"facade":132,"throttle":160,"to-iso-string":161,"clone":95,"each":4,"bind":101}],
160: [function(require, module, exports) {
/**
* Module exports.
*/
module.exports = throttle;
/**
* Returns a new function that, when invoked, invokes `func` at most one time per
* `wait` milliseconds.
*
* @param {Function} func The `Function` instance to wrap.
* @param {Number} wait The minimum number of milliseconds that must elapse in between `func` invokations.
* @return {Function} A new function that wraps the `func` function passed in.
* @api public
*/
function throttle (func, wait) {
var rtn; // return value
var last = 0; // last invokation timestamp
return function throttled () {
var now = new Date().getTime();
var delta = now - last;
if (delta >= wait) {
rtn = func.apply(this, arguments);
last = now;
}
return rtn;
};
}
}, {}],
161: [function(require, module, exports) {
/**
* Expose `toIsoString`.
*/
module.exports = toIsoString;
/**
* Turn a `date` into an ISO string.
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*
* @param {Date} date
* @return {String}
*/
function toIsoString (date) {
return date.getUTCFullYear()
+ '-' + pad(date.getUTCMonth() + 1)
+ '-' + pad(date.getUTCDate())
+ 'T' + pad(date.getUTCHours())
+ ':' + pad(date.getUTCMinutes())
+ ':' + pad(date.getUTCSeconds())
+ '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
+ 'Z';
}
/**
* Pad a `number` with a ten's place zero.
*
* @param {Number} number
* @return {String}
*/
function pad (number) {
var n = number.toString();
return n.length === 1 ? '0' + n : n;
}
}, {}],
28: [function(require, module, exports) {
/**
* Module dependencies.
*/
var alias = require('alias');
var convertDates = require('convert-dates');
var Identify = require('facade').Identify;
var integration = require('analytics.js-integration');
/**
* Expose `Customerio` integration.
*/
var Customerio = module.exports = integration('Customer.io')
.global('_cio')
.option('siteId', '')
.tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');
/**
* Initialize.
*
* http://customer.io/docs/api/javascript.html
*
* @param {Object} page
*/
Customerio.prototype.initialize = function(page){
window._cio = window._cio || [];
(function(){var a,b,c; a = function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })();
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Customerio.prototype.loaded = function(){
return (!! window._cio) && (window._cio.push !== Array.prototype.push);
};
/**
* Identify.
*
* http://customer.io/docs/api/javascript.html#section-Identify_customers
*
* @param {Identify} identify
*/
Customerio.prototype.identify = function(identify){
if (!identify.userId()) return this.debug('user id required');
var traits = identify.traits({ createdAt: 'created' });
traits = alias(traits, { created: 'created_at' });
traits = convertDates(traits, convertDate);
window._cio.identify(traits);
};
/**
* Group.
*
* @param {Group} group
*/
Customerio.prototype.group = function(group){
var traits = group.traits();
var user = this.analytics.user();
traits = alias(traits, function(trait){
return 'Group ' + trait;
});
this.identify(new Identify({
userId: user.id(),
traits: traits
}));
};
/**
* Track.
*
* http://customer.io/docs/api/javascript.html#section-Track_a_custom_event
*
* @param {Track} track
*/
Customerio.prototype.track = function(track){
var properties = track.properties();
properties = convertDates(properties, convertDate);
window._cio.track(track.event(), properties);
};
/**
* Convert a date to the format Customer.io supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate(date){
return Math.floor(date.getTime() / 1000);
}
}, {"alias":162,"convert-dates":163,"facade":132,"analytics.js-integration":88}],
162: [function(require, module, exports) {
var type = require('type');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `alias`.
*/
module.exports = alias;
/**
* Alias an `object`.
*
* @param {Object} obj
* @param {Mixed} method
*/
function alias (obj, method) {
switch (type(method)) {
case 'object': return aliasByDictionary(clone(obj), method);
case 'function': return aliasByFunction(clone(obj), method);
}
}
/**
* Convert the keys in an `obj` using a dictionary of `aliases`.
*
* @param {Object} obj
* @param {Object} aliases
*/
function aliasByDictionary (obj, aliases) {
for (var key in aliases) {
if (undefined === obj[key]) continue;
obj[aliases[key]] = obj[key];
delete obj[key];
}
return obj;
}
/**
* Convert the keys in an `obj` using a `convert` function.
*
* @param {Object} obj
* @param {Function} convert
*/
function aliasByFunction (obj, convert) {
// have to create another object so that ie8 won't infinite loop on keys
var output = {};
for (var key in obj) output[convert(key)] = obj[key];
return output;
}
}, {"type":7,"clone":150}],
163: [function(require, module, exports) {
var is = require('is');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `convertDates`.
*/
module.exports = convertDates;
/**
* Recursively convert an `obj`'s dates to new values.
*
* @param {Object} obj
* @param {Function} convert
* @return {Object}
*/
function convertDates (obj, convert) {
obj = clone(obj);
for (var key in obj) {
var val = obj[key];
if (is.date(val)) obj[key] = convert(val);
if (is.object(val)) obj[key] = convertDates(val, convert);
}
return obj;
}
}, {"is":91,"clone":95}],
29: [function(require, module, exports) {
/**
* Module dependencies.
*/
var alias = require('alias');
var integration = require('analytics.js-integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_dcq');
/**
* Expose `Drip` integration.
*/
var Drip = module.exports = integration('Drip')
.assumesPageview()
.global('_dc')
.global('_dcqi')
.global('_dcq')
.global('_dcs')
.option('account', '')
.tag('<script src="//tag.getdrip.com/{{ account }}.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Drip.prototype.initialize = function(page){
window._dcq = window._dcq || [];
window._dcs = window._dcs || {};
window._dcs.account = this.options.account;
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Drip.prototype.loaded = function(){
return is.object(window._dc);
};
/**
* Track.
*
* @param {Track} track
*/
Drip.prototype.track = function(track){
var props = track.properties();
var cents = track.cents();
if (cents) props.value = cents;
delete props.revenue;
push('track', track.event(), props);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Drip.prototype.identify = function(identify){
push('identify', identify.traits());
};
}, {"alias":162,"analytics.js-integration":88,"is":91,"load-script":128,"global-queue":158}],
30: [function(require, module, exports) {
/**
* Module dependencies.
*/
var extend = require('extend');
var integration = require('analytics.js-integration');
var onError = require('on-error');
var push = require('global-queue')('_errs');
/**
* Expose `Errorception` integration.
*/
var Errorception = module.exports = integration('Errorception')
.assumesPageview()
.global('_errs')
.option('projectId', '')
.option('meta', true)
.tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');
/**
* Initialize.
*
* https://github.com/amplitude/Errorception-Javascript
*
* @param {Object} page
*/
Errorception.prototype.initialize = function(page){
window._errs = window._errs || [this.options.projectId];
onError(push);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Errorception.prototype.loaded = function(){
return !! (window._errs && window._errs.push !== Array.prototype.push);
};
/**
* Identify.
*
* http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html
*
* @param {Object} identify
*/
Errorception.prototype.identify = function(identify){
if (!this.options.meta) return;
var traits = identify.traits();
window._errs = window._errs || [];
window._errs.meta = window._errs.meta || {};
extend(window._errs.meta, traits);
};
}, {"extend":130,"analytics.js-integration":88,"on-error":156,"global-queue":158}],
31: [function(require, module, exports) {
/**
* Module dependencies.
*/
var each = require('each');
var integration = require('analytics.js-integration');
var push = require('global-queue')('_aaq');
/**
* Expose `Evergage` integration.integration.
*/
var Evergage = module.exports = integration('Evergage')
.assumesPageview()
.global('_aaq')
.option('account', '')
.option('dataset', '')
.tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Evergage.prototype.initialize = function(page){
var account = this.options.account;
var dataset = this.options.dataset;
window._aaq = window._aaq || [];
push('setEvergageAccount', account);
push('setDataset', dataset);
push('setUseSiteConfig', true);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Evergage.prototype.loaded = function(){
return !! (window._aaq && window._aaq.push !== Array.prototype.push);
};
/**
* Page.
*
* @param {Page} page
*/
Evergage.prototype.page = function(page){
var props = page.properties();
var name = page.name();
if (name) push('namePage', name);
each(props, function(key, value){
push('setCustomField', key, value, 'page');
});
window.Evergage.init(true);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Evergage.prototype.identify = function(identify){
var id = identify.userId();
if (!id) return;
push('setUser', id);
var traits = identify.traits({
email: 'userEmail',
name: 'userName'
});
each(traits, function(key, value){
push('setUserField', key, value, 'page');
});
};
/**
* Group.
*
* @param {Group} group
*/
Evergage.prototype.group = function(group){
var props = group.traits();
var id = group.groupId();
if (!id) return;
push('setCompany', id);
each(props, function(key, value){
push('setAccountField', key, value, 'page');
});
};
/**
* Track.
*
* @param {Track} track
*/
Evergage.prototype.track = function(track){
push('trackAction', track.event(), track.properties());
};
}, {"each":4,"analytics.js-integration":88,"global-queue":158}],
32: [function(require, module, exports) {
'use strict';
/**
* Module dependencies.
*/
var bind = require('bind');
var domify = require('domify');
var each = require('each');
var extend = require('extend');
var integration = require('analytics.js-integration');
var json = require('json');
/**
* Expose `Extole` integration.
*/
var Extole = module.exports = integration('Extole')
.global('extole')
.option('clientId', '')
.mapping('events')
.tag('main', '<script src="//tags.extole.com/{{ clientId }}/core.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Extole.prototype.initialize = function(){
if (this.loaded()) return this.ready();
this.load('main', bind(this, this.ready));
};
/**
* Loaded?
*
* @return {Boolean}
*/
Extole.prototype.loaded = function(){
return !!window.extole;
};
/**
* Track.
*
* @param {Track} track
*/
Extole.prototype.track = function(track){
var user = this.analytics.user();
var traits = user.traits();
var userId = user.id();
var email = traits.email;
if (!userId && !email) {
return this.debug('User must be identified before `#track` calls');
}
var event = track.event();
var extoleEvents = this.events(event);
if (!extoleEvents.length) {
return this.debug('No events found for %s', event);
}
each(extoleEvents, bind(this, function(extoleEvent){
this._registerConversion(this._createConversionTag({
type: extoleEvent,
params: this._formatConversionParams(event, email, userId, track.properties())
}));
}));
};
/**
* Register a conversion to Extole.
*
* @api private
* @param {HTMLElement} conversionTag An Extole conversion tag.
*/
// TODO: If I understand Extole's lib correctly, this is sometimes async,
// sometimes sync. Should probably refactor this into more predictable/sane
// behavior
Extole.prototype._registerConversion = function(conversionTag){
if (window.extole.main && window.extole.main.fireConversion) {
return window.extole.main.fireConversion(conversionTag);
}
if (window.extole.initializeGo) {
window.extole.initializeGo().andWhenItsReady(function(){
window.extole.main.fireConversion(conversionTag);
});
}
};
/**
* formatConversionParams. Formats details from a Segment track event into a
* data format Extole can accept.
*
* @param {string} event
* @param {string} email
* @param {string|number} userId
* @param {Object} properties The result of calling `track.properties()`.
* @return {Object}
*/
Extole.prototype._formatConversionParams = function(event, email, userId, properties){
var total;
if (properties.total) {
total = properties.total;
delete properties.total;
properties['tag:cart_value'] = total;
}
return extend({
'tag:segment_event': event,
e: email,
partner_conversion_id: userId
}, properties);
};
/**
* Create an Extole conversion tag.
*
* @param {Object} conversion An Extole conversion object.
* @return {HTMLElement}
*/
Extole.prototype._createConversionTag = function(conversion){
return domify('<script type="extole/conversion">' + json.stringify(conversion) + '</script>');
};
}, {"bind":101,"domify":119,"each":4,"extend":130,"analytics.js-integration":88,"json":164}],
164: [function(require, module, exports) {
var json = window.JSON || {};
var stringify = json.stringify;
var parse = json.parse;
module.exports = parse && stringify
? JSON
: require('json-fallback');
}, {"json-fallback":165}],
165: [function(require, module, exports) {
/*
json2.js
2014-02-04
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
(function () {
'use strict';
var JSON = module.exports = {};
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
}, {}],
33: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_fbq');
var each = require('each');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Facebook`
*/
var Facebook = module.exports = integration('Facebook Conversion Tracking')
.global('_fbq')
.option('currency', 'USD')
.tag('<script src="//connect.facebook.net/en_US/fbds.js">')
.mapping('events');
/**
* Initialize Facebook Conversion Tracking
*
* https://developers.facebook.com/docs/ads-for-websites/conversion-pixel-code-migration
*
* @param {Object} page
*/
Facebook.prototype.initialize = function(page){
window._fbq = window._fbq || [];
this.load(this.ready);
window._fbq.loaded = true;
};
/**
* Loaded?
*
* @return {Boolean}
*/
Facebook.prototype.loaded = function(){
return !! (window._fbq && window._fbq.loaded);
};
/**
* Page.
*
* @param {Page} page
*/
Facebook.prototype.page = function(page){
var name = page.fullName();
this.track(page.track(name));
}
/**
* Track.
*
* https://developers.facebook.com/docs/reference/ads-api/custom-audience-website-faq/#fbpixel
*
* @param {Track} track
*/
Facebook.prototype.track = function(track){
var event = track.event();
var events = this.events(event);
var revenue = track.revenue() || 0;
var self = this;
each(events, function(event){
push('track', event, {
value: String(revenue.toFixed(2)),
currency: self.options.currency
});
});
};
}, {"analytics.js-integration":88,"global-queue":158,"each":4}],
34: [function(require, module, exports) {
/**
* Module dependencies.
*/
var push = require('global-queue')('_fxm');
var integration = require('analytics.js-integration');
var Track = require('facade').Track;
var each = require('each');
/**
* Expose `FoxMetrics` integration.
*/
var FoxMetrics = module.exports = integration('FoxMetrics')
.assumesPageview()
.global('_fxm')
.option('appId', '')
.tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');
/**
* Initialize.
*
* http://foxmetrics.com/documentation/apijavascript
*
* @param {Object} page
*/
FoxMetrics.prototype.initialize = function(page){
window._fxm = window._fxm || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
FoxMetrics.prototype.loaded = function(){
return !! (window._fxm && window._fxm.appId);
};
/**
* Page.
*
* @param {Page} page
*/
FoxMetrics.prototype.page = function(page){
var properties = page.proxy('properties');
var category = page.category();
var name = page.name();
this._category = category; // store for later
push(
'_fxm.pages.view',
properties.title, // title
name, // name
category, // category
properties.url, // url
properties.referrer // referrer
);
};
/**
* Identify.
*
* @param {Identify} identify
*/
FoxMetrics.prototype.identify = function(identify){
var id = identify.userId();
if (!id) return;
push(
'_fxm.visitor.profile',
id, // user id
identify.firstName(), // first name
identify.lastName(), // last name
identify.email(), // email
identify.address(), // address
undefined, // social
undefined, // partners
identify.traits() // attributes
);
};
/**
* Track.
*
* @param {Track} track
*/
FoxMetrics.prototype.track = function(track){
var props = track.properties();
var category = this._category || props.category;
push(track.event(), category, props);
};
/**
* Viewed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.viewedProduct = function(track){
ecommerce('productview', track);
};
/**
* Removed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.removedProduct = function(track){
ecommerce('removecartitem', track);
};
/**
* Added product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.addedProduct = function(track){
ecommerce('cartitem', track);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.completedOrder = function(track){
var orderId = track.orderId();
// transaction
push(
'_fxm.ecommerce.order',
orderId,
track.subtotal(),
track.shipping(),
track.tax(),
track.city(),
track.state(),
track.zip(),
track.quantity()
);
// items
each(track.products(), function(product){
var track = new Track({ properties: product });
ecommerce('purchaseitem', track, [
track.quantity(),
track.price(),
orderId
]);
});
};
/**
* Track ecommerce `event` with `track`
* with optional `arr` to append.
*
* @param {String} event
* @param {Track} track
* @param {Array} arr
* @api private
*/
function ecommerce(event, track, arr){
push.apply(null, [
'_fxm.ecommerce.' + event,
track.id() || track.sku(),
track.name(),
track.category()
].concat(arr || []));
}
}, {"global-queue":158,"analytics.js-integration":88,"facade":132,"each":4}],
35: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var bind = require('bind');
var when = require('when');
var is = require('is');
/**
* Expose `Frontleaf` integration.
*/
var Frontleaf = module.exports = integration('Frontleaf')
.global('_fl')
.global('_flBaseUrl')
.option('baseUrl', 'https://api.frontleaf.com')
.option('token', '')
.option('stream', '')
.option('trackNamedPages', false)
.option('trackCategorizedPages', false)
.tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');
/**
* Initialize.
*
* http://docs.frontleaf.com/#/technical-implementation/tracking-customers/tracking-beacon
*
* @param {Object} page
*/
Frontleaf.prototype.initialize = function(page){
window._fl = window._fl || [];
window._flBaseUrl = window._flBaseUrl || this.options.baseUrl;
this._push('setApiToken', this.options.token);
this._push('setStream', this.options.stream);
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load({ baseUrl: window._flBaseUrl }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Frontleaf.prototype.loaded = function(){
return is.array(window._fl) && window._fl.ready === true;
};
/**
* Identify.
*
* @param {Identify} identify
*/
Frontleaf.prototype.identify = function(identify){
var userId = identify.userId();
if (userId) {
this._push('setUser', {
id: userId,
name: identify.name() || identify.username(),
data: clean(identify.traits())
});
}
};
/**
* Group.
*
* @param {Group} group
*/
Frontleaf.prototype.group = function(group){
var groupId = group.groupId();
if (groupId) {
this._push('setAccount', {
id: groupId,
name: group.proxy('traits.name'),
data: clean(group.traits())
});
}
};
/**
* Page.
*
* @param {Page} page
*/
Frontleaf.prototype.page = function(page){
var category = page.category();
var name = page.fullName();
var opts = this.options;
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Track.
*
* @param {Track} track
*/
Frontleaf.prototype.track = function(track){
var event = track.event();
this._push('event', event, clean(track.properties()));
};
/**
* Push a command onto the global Frontleaf queue.
*
* @param {String} command
* @return {Object} args
* @api private
*/
Frontleaf.prototype._push = function(command){
var args = [].slice.call(arguments, 1);
window._fl.push(function(t){ t[command].apply(command, args); });
};
/**
* Clean all nested objects and arrays.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function clean(obj){
var ret = {};
// Remove traits/properties that are already represented
// outside of the data container
var excludeKeys = ["id","name","firstName","lastName"];
var len = excludeKeys.length;
for (var i = 0; i < len; i++) {
clear(obj, excludeKeys[i]);
}
// Flatten nested hierarchy, preserving arrays
obj = flatten(obj);
// Discard nulls, represent arrays as comma-separated strings
for (var key in obj) {
var val = obj[key];
if (null == val) {
continue;
}
if (is.array(val)) {
ret[key] = val.toString();
continue;
}
ret[key] = val;
}
return ret;
}
/**
* Remove a property from an object if set.
*
* @param {Object} obj
* @param {String} key
* @api private
*/
function clear(obj, key){
if (obj.hasOwnProperty(key)) {
delete obj[key];
}
}
/**
* Flatten a nested object into a single level space-delimited
* hierarchy.
*
* Based on https://github.com/hughsk/flat
*
* @param {Object} source
* @return {Object}
* @api private
*/
function flatten(source){
var output = {};
function step(object, prev){
for (var key in object) {
var value = object[key];
var newKey = prev ? prev + ' ' + key : key;
if (!is.array(value) && is.object(value)) {
return step(value, newKey);
}
output[newKey] = value;
}
}
step(source);
return output;
}
}, {"analytics.js-integration":88,"bind":101,"when":131,"is":91}],
36: [function(require, module, exports) {
/**
* Module dependencies.
*/
var foldl = require('foldl');
var is = require('is');
var camel = require('to-camel-case');
var integration = require('analytics.js-integration');
/**
* Expose `FullStory` integration.
*
* https://www.fullstory.com/docs/developer
*/
var FullStory = module.exports = integration('FullStory')
.option('org', '')
.option('debug', false)
.tag('<script src="https://www.fullstory.com/s/fs.js"></script>')
/**
* Initialize.
*/
FullStory.prototype.initialize = function(){
var self = this;
window._fs_debug = this.options.debug;
window._fs_host = 'www.fullstory.com';
window._fs_org = this.options.org;
(function(m,n,e,t,l,o,g,y){
g=m[e]=function(a,b){g.q?g.q.push([a,b]):g._api(a,b);};g.q=[];
// jscs:disable
g.identify=function(i,v){g(l,{uid:i});if(v)g(l,v)};g.setUserVars=function(v){FS(l,v)};
// jscs:enable
g.setSessionVars=function(v){FS('session',v)};g.setPageVars=function(v){FS('page',v)};
self.ready();
self.load();
})(window,document,'FS','script','user');
};
/**
* Loaded?
*
* @return {Boolean}
*/
FullStory.prototype.loaded = function(){
return !! window.FS;
};
/**
* Identify.
*
* @param {Identify} identify
*/
FullStory.prototype.identify = function(identify){
var id = identify.userId() || identify.anonymousId();
var traits = identify.traits({ name: 'displayName' });
var newTraits = foldl(function(results, value, key){
if (key !== 'id') results[key === 'displayName' || key === 'email' ? key : convert(key, value)] = value;
return results;
}, {}, traits);
window.FS.identify(String(id), newTraits);
};
/**
* Convert to FullStory format.
*
* @param {String} trait
* @param {Property} value
*/
function convert (trait, value) {
trait = camel(trait);
if (is.string(value)) return trait += '_str';
if (isInt(value)) return trait += '_int';
if (isFloat(value)) return trait += '_real';
if (is.date(value)) return trait += '_date';
if (is.boolean(value)) return trait += '_bool';
}
/**
* Check if n is a float.
*/
function isFloat(n) {
return n === +n && n !== (n|0);
}
/**
* Check if n is an integer.
*/
function isInt(n) {
return n === +n && n === (n|0);
}
}, {"foldl":166,"is":91,"to-camel-case":167,"analytics.js-integration":88}],
166: [function(require, module, exports) {
'use strict';
/**
* Module dependencies.
*/
var each = require('each');
/**
* Reduces all the values in a collection down into a single value. Does so by iterating through the
* collection from left to right, repeatedly calling an `iterator` function and passing to it four
* arguments: `(accumulator, value, index, collection)`.
*
* Returns the final return value of the `iterator` function.
*
* @name foldl
* @api public
* @param {Function} iterator The function to invoke per iteration.
* @param {*} accumulator The initial accumulator value, passed to the first invocation of `iterator`.
* @param {Array|Object} collection The collection to iterate over.
* @return {*} The return value of the final call to `iterator`.
* @example
* foldl(function(total, n) {
* return total + n;
* }, 0, [1, 2, 3]);
* //=> 6
*
* var phonebook = { bob: '555-111-2345', tim: '655-222-6789', sheila: '655-333-1298' };
*
* foldl(function(results, phoneNumber) {
* if (phoneNumber[0] === '6') {
* return results.concat(phoneNumber);
* }
* return results;
* }, [], phonebook);
* // => ['655-222-6789', '655-333-1298']
*/
var foldl = function foldl(iterator, accumulator, collection) {
if (typeof iterator !== 'function') {
throw new TypeError('Expected a function but received a ' + typeof iterator);
}
each(function(val, i, collection) {
accumulator = iterator(accumulator, val, i, collection);
}, collection);
return accumulator;
};
/**
* Exports.
*/
module.exports = foldl;
}, {"each":168}],
168: [function(require, module, exports) {
'use strict';
/**
* Module dependencies.
*/
var keys = require('keys');
/**
* Object.prototype.toString reference.
*/
var objToString = Object.prototype.toString;
/**
* Tests if a value is a number.
*
* @name isNumber
* @api private
* @param {*} val The value to test.
* @return {boolean} Returns `true` if `val` is a number, otherwise `false`.
*/
// TODO: Move to library
var isNumber = function isNumber(val) {
var type = typeof val;
return type === 'number' || (type === 'object' && objToString.call(val) === '[object Number]');
};
/**
* Tests if a value is an array.
*
* @name isArray
* @api private
* @param {*} val The value to test.
* @return {boolean} Returns `true` if the value is an array, otherwise `false`.
*/
// TODO: Move to library
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function isArray(val) {
return objToString.call(val) === '[object Array]';
};
/**
* Tests if a value is array-like. Array-like means the value is not a function and has a numeric
* `.length` property.
*
* @name isArrayLike
* @api private
* @param {*} val
* @return {boolean}
*/
// TODO: Move to library
var isArrayLike = function isArrayLike(val) {
return val != null && (isArray(val) || (val !== 'function' && isNumber(val.length)));
};
/**
* Internal implementation of `each`. Works on arrays and array-like data structures.
*
* @name arrayEach
* @api private
* @param {Function(value, key, collection)} iterator The function to invoke per iteration.
* @param {Array} array The array(-like) structure to iterate over.
* @return {undefined}
*/
var arrayEach = function arrayEach(iterator, array) {
for (var i = 0; i < array.length; i += 1) {
// Break iteration early if `iterator` returns `false`
if (iterator(array[i], i, array) === false) {
break;
}
}
};
/**
* Internal implementation of `each`. Works on objects.
*
* @name baseEach
* @api private
* @param {Function(value, key, collection)} iterator The function to invoke per iteration.
* @param {Object} object The object to iterate over.
* @return {undefined}
*/
var baseEach = function baseEach(iterator, object) {
var ks = keys(object);
for (var i = 0; i < ks.length; i += 1) {
// Break iteration early if `iterator` returns `false`
if (iterator(object[ks[i]], ks[i], object) === false) {
break;
}
}
};
/**
* Iterate over an input collection, invoking an `iterator` function for each element in the
* collection and passing to it three arguments: `(value, index, collection)`. The `iterator`
* function can end iteration early by returning `false`.
*
* @name each
* @api public
* @param {Function(value, key, collection)} iterator The function to invoke per iteration.
* @param {Array|Object|string} collection The collection to iterate over.
* @return {undefined} Because `each` is run only for side effects, always returns `undefined`.
* @example
* var log = console.log.bind(console);
*
* each(log, ['a', 'b', 'c']);
* //-> 'a', 0, ['a', 'b', 'c']
* //-> 'b', 1, ['a', 'b', 'c']
* //-> 'c', 2, ['a', 'b', 'c']
* //=> undefined
*
* each(log, 'tim');
* //-> 't', 2, 'tim'
* //-> 'i', 1, 'tim'
* //-> 'm', 0, 'tim'
* //=> undefined
*
* // Note: Iteration order not guaranteed across environments
* each(log, { name: 'tim', occupation: 'enchanter' });
* //-> 'tim', 'name', { name: 'tim', occupation: 'enchanter' }
* //-> 'enchanter', 'occupation', { name: 'tim', occupation: 'enchanter' }
* //=> undefined
*/
var each = function each(iterator, collection) {
return (isArrayLike(collection) ? arrayEach : baseEach).call(this, iterator, collection);
};
/**
* Exports.
*/
module.exports = each;
}, {"keys":169}],
169: [function(require, module, exports) {
'use strict';
/**
* charAt reference.
*/
var strCharAt = String.prototype.charAt;
/**
* Returns the character at a given index.
*
* @param {string} str
* @param {number} index
* @return {string|undefined}
*/
// TODO: Move to a library
var charAt = function(str, index) {
return strCharAt.call(str, index);
};
/**
* hasOwnProperty reference.
*/
var hop = Object.prototype.hasOwnProperty;
/**
* Object.prototype.toString reference.
*/
var toStr = Object.prototype.toString;
/**
* hasOwnProperty, wrapped as a function.
*
* @name has
* @api private
* @param {*} context
* @param {string|number} prop
* @return {boolean}
*/
// TODO: Move to a library
var has = function has(context, prop) {
return hop.call(context, prop);
};
/**
* Returns true if a value is a string, otherwise false.
*
* @name isString
* @api private
* @param {*} val
* @return {boolean}
*/
// TODO: Move to a library
var isString = function isString(val) {
return toStr.call(val) === '[object String]';
};
/**
* Returns true if a value is array-like, otherwise false. Array-like means a
* value is not null, undefined, or a function, and has a numeric `length`
* property.
*
* @name isArrayLike
* @api private
* @param {*} val
* @return {boolean}
*/
// TODO: Move to a library
var isArrayLike = function isArrayLike(val) {
return val != null && (typeof val !== 'function' && typeof val.length === 'number');
};
/**
* indexKeys
*
* @name indexKeys
* @api private
* @param {} target
* @param {} pred
* @return {Array}
*/
var indexKeys = function indexKeys(target, pred) {
pred = pred || has;
var results = [];
for (var i = 0, len = target.length; i < len; i += 1) {
if (pred(target, i)) {
results.push(String(i));
}
}
return results;
};
/**
* Returns an array of all the owned
*
* @name objectKeys
* @api private
* @param {*} target
* @param {Function} pred Predicate function used to include/exclude values from
* the resulting array.
* @return {Array}
*/
var objectKeys = function objectKeys(target, pred) {
pred = pred || has;
var results = [];
for (var key in target) {
if (pred(target, key)) {
results.push(String(key));
}
}
return results;
};
/**
* Creates an array composed of all keys on the input object. Ignores any non-enumerable properties.
* More permissive than the native `Object.keys` function (non-objects will not throw errors).
*
* @name keys
* @api public
* @category Object
* @param {Object} source The value to retrieve keys from.
* @return {Array} An array containing all the input `source`'s keys.
* @example
* keys({ likes: 'avocado', hates: 'pineapple' });
* //=> ['likes', 'pineapple'];
*
* // Ignores non-enumerable properties
* var hasHiddenKey = { name: 'Tim' };
* Object.defineProperty(hasHiddenKey, 'hidden', {
* value: 'i am not enumerable!',
* enumerable: false
* })
* keys(hasHiddenKey);
* //=> ['name'];
*
* // Works on arrays
* keys(['a', 'b', 'c']);
* //=> ['0', '1', '2']
*
* // Skips unpopulated indices in sparse arrays
* var arr = [1];
* arr[4] = 4;
* keys(arr);
* //=> ['0', '4']
*/
module.exports = function keys(source) {
if (source == null) {
return [];
}
// IE6-8 compatibility (string)
if (isString(source)) {
return indexKeys(source, charAt);
}
// IE6-8 compatibility (arguments)
if (isArrayLike(source)) {
return indexKeys(source, has);
}
return objectKeys(source);
};
}, {}],
167: [function(require, module, exports) {
var toSpace = require('to-space-case');
/**
* Expose `toCamelCase`.
*/
module.exports = toCamelCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toCamelCase (string) {
return toSpace(string).replace(/\s(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
}, {"to-space-case":120}],
37: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_gauges');
/**
* Expose `Gauges` integration.
*/
var Gauges = module.exports = integration('Gauges')
.assumesPageview()
.global('_gauges')
.option('siteId', '')
.tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');
/**
* Initialize Gauges.
*
* http://get.gaug.es/documentation/tracking/
*
* @param {Object} page
*/
Gauges.prototype.initialize = function(page){
window._gauges = window._gauges || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Gauges.prototype.loaded = function(){
return !! (window._gauges && window._gauges.push !== Array.prototype.push);
};
/**
* Page.
*
* @param {Page} page
*/
Gauges.prototype.page = function(page){
push('track');
};
}, {"analytics.js-integration":88,"global-queue":158}],
38: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var onBody = require('on-body');
/**
* Expose `GetSatisfaction` integration.
*/
var GetSatisfaction = module.exports = integration('Get Satisfaction')
.assumesPageview()
.global('GSFN')
.option('widgetId', '')
.tag('<script src="https://loader.engage.gsfn.us/loader.js">');
/**
* Initialize.
*
* https://console.getsatisfaction.com/start/101022?signup=true#engage
*
* @param {Object} page
*/
GetSatisfaction.prototype.initialize = function(page){
var self = this;
var widget = this.options.widgetId;
var div = document.createElement('div');
var id = div.id = 'getsat-widget-' + widget;
onBody(function(body){ body.appendChild(div); });
// usually the snippet is sync, so wait for it before initializing the tab
this.load(function(){
window.GSFN.loadWidget(widget, { containerId: id });
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
GetSatisfaction.prototype.loaded = function(){
return !! window.GSFN;
};
}, {"analytics.js-integration":88,"on-body":129}],
39: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_gaq');
var length = require('object').length;
var canonical = require('canonical');
var useHttps = require('use-https');
var Track = require('facade').Track;
var callback = require('callback');
var defaults = require('defaults');
var load = require('load-script');
var keys = require('object').keys;
var select = require('select');
var dot = require('obj-case');
var each = require('each');
var type = require('type');
var url = require('url');
var is = require('is');
var group;
var user;
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(GA);
group = analytics.group();
user = analytics.user();
};
/**
* Expose `GA` integration.
*
* http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate
*/
var GA = exports.Integration = integration('Google Analytics')
.readyOnLoad()
.global('ga')
.global('gaplugins')
.global('_gaq')
.global('GoogleAnalyticsObject')
.option('anonymizeIp', false)
.option('classic', false)
.option('domain', 'auto')
.option('doubleClick', false)
.option('enhancedEcommerce', false)
.option('enhancedLinkAttribution', false)
.option('nonInteraction', false)
.option('ignoredReferrers', null)
.option('includeSearch', false)
.option('siteSpeedSampleRate', 1)
.option('trackingId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('sendUserId', false)
.option('metrics', {})
.option('dimensions', {})
.tag('library', '<script src="//www.google-analytics.com/analytics.js">')
.tag('double click', '<script src="//stats.g.doubleclick.net/dc.js">')
.tag('http', '<script src="http://www.google-analytics.com/ga.js">')
.tag('https', '<script src="https://ssl.google-analytics.com/ga.js">');
/**
* On `construct` swap any config-based methods to the proper implementation.
*/
GA.on('construct', function(integration){
if (integration.options.classic) {
integration.initialize = integration.initializeClassic;
integration.loaded = integration.loadedClassic;
integration.page = integration.pageClassic;
integration.track = integration.trackClassic;
integration.completedOrder = integration.completedOrderClassic;
} else if (integration.options.enhancedEcommerce) {
integration.viewedProduct = integration.viewedProductEnhanced;
integration.clickedProduct = integration.clickedProductEnhanced;
integration.addedProduct = integration.addedProductEnhanced;
integration.removedProduct = integration.removedProductEnhanced;
integration.startedOrder = integration.startedOrderEnhanced;
integration.viewedCheckoutStep = integration.viewedCheckoutStepEnhanced;
integration.completedCheckoutStep = integration.completedCheckoutStepEnhanced;
integration.updatedOrder = integration.updatedOrderEnhanced;
integration.completedOrder = integration.completedOrderEnhanced;
integration.refundedOrder = integration.refundedOrderEnhanced;
integration.viewedPromotion = integration.viewedPromotionEnhanced;
integration.clickedPromotion = integration.clickedPromotionEnhanced;
}
});
/**
* Initialize.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced
*/
GA.prototype.initialize = function(){
var opts = this.options;
// setup the tracker globals
window.GoogleAnalyticsObject = 'ga';
window.ga = window.ga || function(){
window.ga.q = window.ga.q || [];
window.ga.q.push(arguments);
};
window.ga.l = new Date().getTime();
if (window.location.hostname === 'localhost') opts.domain = 'none';
window.ga('create', opts.trackingId, {
cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string
siteSpeedSampleRate: opts.siteSpeedSampleRate,
allowLinker: true
});
// display advertising
if (opts.doubleClick) {
window.ga('require', 'displayfeatures');
}
// send global id
if (opts.sendUserId && user.id()) {
window.ga('set', 'userId', user.id());
}
// anonymize after initializing, otherwise a warning is shown
// in google analytics debugger
if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true);
// custom dimensions & metrics
var custom = metrics(user.traits(), opts);
if (length(custom)) window.ga('set', custom);
this.load('library', this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
GA.prototype.loaded = function(){
return !! window.gaplugins;
};
/**
* Page.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
* https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications#multiple-hits
*
*
* @param {Page} page
*/
GA.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
var campaign = page.proxy('context.campaign') || {};
var pageview = {};
var pagePath = path(props, this.options);
var pageTitle = name || props.title;
var track;
this._category = category; // store for later
pageview.page = pagePath;
pageview.title = pageTitle;
pageview.location = props.url;
if (campaign.name) pageview.campaignName = campaign.name;
if (campaign.source) pageview.campaignSource = campaign.source;
if (campaign.medium) pageview.campaignMedium = campaign.medium;
if (campaign.content) pageview.campaignContent = campaign.content;
if (campaign.term) pageview.campaignKeyword = campaign.term;
// custom dimensions and metrics
var custom = metrics(props, opts);
if (length(custom)) window.ga('set', custom);
// set
window.ga('set', { page: pagePath, title: pageTitle });
// send
window.ga('send', 'pageview', pageview);
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { nonInteraction: 1 });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { nonInteraction: 1 });
}
};
/**
* Identify.
*
* @param {Identify} event
*/
GA.prototype.identify = function(identify){
var opts = this.options;
//set userId
if (opts.sendUserId && identify.userId()) {
window.ga('set', 'userId', identify.userId());
}
//set dimensions
var custom = metrics(user.traits(), opts);
if (length(custom)) window.ga('set', custom);
};
/**
* Track.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/events
* https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference
*
* @param {Track} event
*/
GA.prototype.track = function(track, options){
var contextOpts = track.options(this.name);
var interfaceOpts = this.options;
var opts = defaults(options || {}, contextOpts);
opts = defaults(opts, interfaceOpts);
var props = track.properties();
var campaign = track.proxy('context.campaign') || {};
// custom dimensions & metrics
var custom = metrics(props, interfaceOpts);
if (length(custom)) window.ga('set', custom);
var payload = {
eventAction: track.event(),
eventCategory: props.category || this._category || 'All',
eventLabel: props.label,
eventValue: formatValue(props.value || track.revenue()),
nonInteraction: !!(props.nonInteraction || opts.nonInteraction)
};
if (campaign.name) payload.campaignName = campaign.name;
if (campaign.source) payload.campaignSource = campaign.source;
if (campaign.medium) payload.campaignMedium = campaign.medium;
if (campaign.content) payload.campaignContent = campaign.content;
if (campaign.term) payload.campaignKeyword = campaign.term;
window.ga('send', 'event', payload);
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce
* https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#multicurrency
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrder = function(track){
var total = track.total() || track.revenue() || 0;
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
// orderId is required.
if (!orderId) return;
// require ecommerce
if (!this.ecommerce) {
window.ga('require', 'ecommerce');
this.ecommerce = true;
}
// add transaction
window.ga('ecommerce:addTransaction', {
affiliation: props.affiliation,
shipping: track.shipping(),
revenue: total,
tax: track.tax(),
id: orderId,
currency: track.currency()
});
// add products
each(products, function(product){
var productTrack = createProductTrack(track, product);
window.ga('ecommerce:addItem', {
category: productTrack.category(),
quantity: productTrack.quantity(),
price: productTrack.price(),
name: productTrack.name(),
sku: productTrack.sku(),
id: orderId,
currency: productTrack.currency()
});
});
// send
window.ga('ecommerce:send');
};
/**
* Initialize (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*/
GA.prototype.initializeClassic = function(){
var opts = this.options;
var anonymize = opts.anonymizeIp;
var db = opts.doubleClick;
var domain = opts.domain;
var enhanced = opts.enhancedLinkAttribution;
var ignore = opts.ignoredReferrers;
var sample = opts.siteSpeedSampleRate;
window._gaq = window._gaq || [];
push('_setAccount', opts.trackingId);
push('_setAllowLinker', true);
if (anonymize) push('_gat._anonymizeIp');
if (domain) push('_setDomainName', domain);
if (sample) push('_setSiteSpeedSampleRate', sample);
if (enhanced) {
var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:';
var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
push('_require', 'inpage_linkid', pluginUrl);
}
if (ignore) {
if (!is.array(ignore)) ignore = [ignore];
each(ignore, function(domain){
push('_addIgnoredRef', domain);
});
}
if (this.options.doubleClick) {
this.load('double click', this.ready);
} else {
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
}
};
/**
* Loaded? (classic)
*
* @return {Boolean}
*/
GA.prototype.loadedClassic = function(){
return !! (window._gaq && window._gaq.push !== Array.prototype.push);
};
/**
* Page (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*
* @param {Page} page
*/
GA.prototype.pageClassic = function(page){
var opts = page.options(this.name);
var category = page.category();
var props = page.properties();
var name = page.fullName();
var track;
push('_trackPageview', path(props, this.options));
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { nonInteraction: 1 });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { nonInteraction: 1 });
}
};
/**
* Track (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking
*
* @param {Track} track
*/
GA.prototype.trackClassic = function(track, options){
var opts = options || track.options(this.name);
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var category = this._category || props.category || 'All';
var label = props.label;
var value = formatValue(revenue || props.value);
var nonInteraction = !!(props.nonInteraction || opts.nonInteraction);
push('_trackEvent', category, event, label, value, nonInteraction);
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce
* https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#localcurrencies
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrderClassic = function(track){
var total = track.total() || track.revenue() || 0;
var orderId = track.orderId();
var products = track.products() || [];
var props = track.properties();
var currency = track.currency();
// required
if (!orderId) return;
// add transaction
push('_addTrans',
orderId,
props.affiliation,
total,
track.tax(),
track.shipping(),
track.city(),
track.state(),
track.country());
// add items
each(products, function(product){
var track = new Track({ properties: product });
push('_addItem',
orderId,
track.sku(),
track.name(),
track.category(),
track.price(),
track.quantity());
});
// send
push('_set', 'currencyCode', currency);
push('_trackTrans');
};
/**
* Return the path based on `properties` and `options`.
*
* @param {Object} properties
* @param {Object} options
*/
function path(properties, options) {
if (!properties) return;
var str = properties.path;
if (options.includeSearch && properties.search) str += properties.search;
return str;
}
/**
* Format the value property to Google's liking.
*
* @param {Number} value
* @return {Number}
*/
function formatValue(value) {
if (!value || value < 0) return 0;
return Math.round(value);
}
/**
* Map google's custom dimensions & metrics with `obj`.
*
* Example:
*
* metrics({ revenue: 1.9 }, { { metrics : { revenue: 'metric8' } });
* // => { metric8: 1.9 }
*
* metrics({ revenue: 1.9 }, {});
* // => {}
*
* @param {Object} obj
* @param {Object} data
* @return {Object|null}
* @api private
*/
function metrics(obj, data){
var dimensions = data.dimensions;
var metrics = data.metrics;
var names = keys(metrics).concat(keys(dimensions));
var ret = {};
for (var i = 0; i < names.length; ++i) {
var name = names[i];
var key = metrics[name] || dimensions[name];
var value = dot(obj, name) || obj[name];
if (null == value) continue;
ret[key] = value;
}
return ret;
}
/**
* Loads ec.js (unless already loaded)
*/
GA.prototype.loadEnhancedEcommerce = function(track){
if (!this.enhancedEcommerceLoaded) {
window.ga('require', 'ec');
this.enhancedEcommerceLoaded = true;
}
// Ensure we set currency for every hit
window.ga('set', '&cu', track.currency());
};
/**
* Pushes an event and all previously set EE data to GA.
*/
GA.prototype.pushEnhancedEcommerce = function(track){
// Send a custom non-interaction event to ensure all EE data is pushed.
// Without doing this we'd need to require page display after setting EE data.
ga('send', 'event', track.category() || 'EnhancedEcommerce', track.event(), { nonInteraction: 1 });
};
/**
* Started order - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps
*
* @param {Track} track
*/
GA.prototype.startedOrderEnhanced = function(track){
// same as viewed checkout step #1
this.viewedCheckoutStep(track);
};
/**
* Updated order - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps
*
* @param {Track} track
*/
GA.prototype.updatedOrderEnhanced = function(track){
// Same event as started order - will override
this.startedOrderEnhanced(track);
};
/**
* Viewed checkout step - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps
*
* @param {Track} track
*/
GA.prototype.viewedCheckoutStepEnhanced = function(track){
var products = track.products();
var props = track.properties();
var options = extractCheckoutOptions(props);
this.loadEnhancedEcommerce(track);
each(products, function(product){
var productTrack = createProductTrack(track, product);
enhancedEcommerceTrackProduct(productTrack);
});
window.ga('ec:setAction','checkout', {
step: props.step || 1,
option: options || undefined
});
this.pushEnhancedEcommerce(track);
};
/**
* Completed checkout step - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-options
*
* @param {Track} track
*/
GA.prototype.completedCheckoutStepEnhanced = function(track){
var props = track.properties();
var options = extractCheckoutOptions(props);
// Only send an event if we have step and options to update
if (!props.step || !options) return;
this.loadEnhancedEcommerce(track);
window.ga('ec:setAction', 'checkout_option', {
step: props.step || 1,
option: options
});
window.ga('send', 'event', 'Checkout', 'Option');
};
/**
* Completed order - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-transactions
*
* @param {Track} track
*/
GA.prototype.completedOrderEnhanced = function(track){
var total = track.total() || track.revenue() || 0;
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
// orderId is required.
if (!orderId) return;
this.loadEnhancedEcommerce(track);
each(products, function(product){
var productTrack = createProductTrack(track, product);
enhancedEcommerceTrackProduct(productTrack);
});
window.ga('ec:setAction', 'purchase', {
id: orderId,
affiliation: props.affiliation,
revenue: total,
tax: track.tax(),
shipping: track.shipping(),
coupon: track.coupon()
});
this.pushEnhancedEcommerce(track);
};
/**
* Refunded order - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-refunds
*
* @param {Track} track
*/
GA.prototype.refundedOrderEnhanced = function(track){
var orderId = track.orderId();
var products = track.products();
// orderId is required.
if (!orderId) return;
this.loadEnhancedEcommerce(track);
// Without any products it's a full refund
each(products, function(product){
var track = new Track({ properties: product });
window.ga('ec:addProduct', {
id: track.id() || track.sku(),
quantity: track.quantity()
});
});
window.ga('ec:setAction', 'refund', {
id: orderId
});
this.pushEnhancedEcommerce(track);
};
/**
* Added product - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#add-remove-cart
*
* @param {Track} track
*/
GA.prototype.addedProductEnhanced = function(track){
this.loadEnhancedEcommerce(track);
enhancedEcommerceProductAction(track, 'add');
this.pushEnhancedEcommerce(track);
};
/**
* Removed product - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#add-remove-cart
*
* @param {Track} track
*/
GA.prototype.removedProductEnhanced = function(track){
this.loadEnhancedEcommerce(track);
enhancedEcommerceProductAction(track, 'remove');
this.pushEnhancedEcommerce(track);
};
/**
* Viewed product details - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-detail-view
*
* @param {Track} track
*/
GA.prototype.viewedProductEnhanced = function(track){
this.loadEnhancedEcommerce(track);
enhancedEcommerceProductAction(track, 'detail');
this.pushEnhancedEcommerce(track);
};
/**
* Clicked product - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-actions
*
* @param {Track} track
*/
GA.prototype.clickedProductEnhanced = function(track){
var props = track.properties();
this.loadEnhancedEcommerce(track);
enhancedEcommerceProductAction(track, 'click', {
list: props.list
});
this.pushEnhancedEcommerce(track);
};
/**
* Viewed promotion - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-promo-impressions
*
* @param {Track} track
*/
GA.prototype.viewedPromotionEnhanced = function(track){
var props = track.properties();
this.loadEnhancedEcommerce(track);
window.ga('ec:addPromo', {
id: track.id(),
name: track.name(),
creative: props.creative,
position: props.position
});
this.pushEnhancedEcommerce(track);
};
/**
* Clicked promotion - Enhanced Ecommerce
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-promo-clicks
*
* @param {Track} track
*/
GA.prototype.clickedPromotionEnhanced = function(track){
var props = track.properties();
this.loadEnhancedEcommerce(track);
window.ga('ec:addPromo', {
id: track.id(),
name: track.name(),
creative: props.creative,
position: props.position
});
ga('ec:setAction', 'promo_click', {});
this.pushEnhancedEcommerce(track);
};
/**
* Enhanced ecommerce track product.
*
* Simple helper so that we don't repeat `ec:addProduct` everywhere.
*
* @param {Track} track
*/
function enhancedEcommerceTrackProduct(track){
var props = track.properties();
window.ga('ec:addProduct', {
id: track.id() || track.sku(),
name: track.name(),
category: track.category(),
quantity: track.quantity(),
price: track.price(),
brand: props.brand,
variant: props.variant,
currency: track.currency()
});
}
/**
* Set `action` on `track` with `data`.
*
* @param {Track} track
* @param {String} action
* @param {Object} data
*/
function enhancedEcommerceProductAction(track, action, data){
enhancedEcommerceTrackProduct(track);
window.ga('ec:setAction', action, data || {});
}
/**
* Extracts checkout options.
*
* @param {Object} props
* @return {Null|String}
*/
function extractCheckoutOptions(props){
var options = [
props.paymentMethod,
props.shippingMethod
];
// Remove all nulls, empty strings, zeroes, and join with commas.
var valid = select(options, function(e){return e; });
return valid.length > 0 ? valid.join(', ') : null;
}
/**
* Creates a track out of product properties.
*
* @param {Track} track
* @param {Object} properties
* @return {Track}
*/
function createProductTrack(track, properties) {
properties.currency = properties.currency || track.currency();
return new Track({ properties: properties });
}
}, {"analytics.js-integration":88,"global-queue":158,"object":170,"canonical":171,"use-https":90,"facade":132,"callback":94,"defaults":157,"load-script":128,"select":172,"obj-case":92,"each":4,"type":113,"url":173,"is":91}],
170: [function(require, module, exports) {
/**
* HOP ref.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Return own keys in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.keys = Object.keys || function(obj){
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
/**
* Return own values in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.values = function(obj){
var vals = [];
for (var key in obj) {
if (has.call(obj, key)) {
vals.push(obj[key]);
}
}
return vals;
};
/**
* Merge `b` into `a`.
*
* @param {Object} a
* @param {Object} b
* @return {Object} a
* @api public
*/
exports.merge = function(a, b){
for (var key in b) {
if (has.call(b, key)) {
a[key] = b[key];
}
}
return a;
};
/**
* Return length of `obj`.
*
* @param {Object} obj
* @return {Number}
* @api public
*/
exports.length = function(obj){
return exports.keys(obj).length;
};
/**
* Check if `obj` is empty.
*
* @param {Object} obj
* @return {Boolean}
* @api public
*/
exports.isEmpty = function(obj){
return 0 == exports.length(obj);
};
}, {}],
171: [function(require, module, exports) {
module.exports = function canonical () {
var tags = document.getElementsByTagName('link');
for (var i = 0, tag; tag = tags[i]; i++) {
if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href');
}
};
}, {}],
172: [function(require, module, exports) {
/**
* Module dependencies.
*/
var toFunction = require('to-function');
/**
* Filter the given `arr` with callback `fn(val, i)`,
* when a truthy value is return then `val` is included
* in the array returned.
*
* @param {Array} arr
* @param {Function} fn
* @return {Array}
* @api public
*/
module.exports = function(arr, fn){
var ret = [];
fn = toFunction(fn);
for (var i = 0; i < arr.length; ++i) {
if (fn(arr[i], i)) {
ret.push(arr[i]);
}
}
return ret;
};
}, {"to-function":174}],
174: [function(require, module, exports) {
/**
* Module Dependencies
*/
var expr;
try {
expr = require('props');
} catch(e) {
expr = require('component-props');
}
/**
* Expose `toFunction()`.
*/
module.exports = toFunction;
/**
* Convert `obj` to a `Function`.
*
* @param {Mixed} obj
* @return {Function}
* @api private
*/
function toFunction(obj) {
switch ({}.toString.call(obj)) {
case '[object Object]':
return objectToFunction(obj);
case '[object Function]':
return obj;
case '[object String]':
return stringToFunction(obj);
case '[object RegExp]':
return regexpToFunction(obj);
default:
return defaultToFunction(obj);
}
}
/**
* Default to strict equality.
*
* @param {Mixed} val
* @return {Function}
* @api private
*/
function defaultToFunction(val) {
return function(obj){
return val === obj;
};
}
/**
* Convert `re` to a function.
*
* @param {RegExp} re
* @return {Function}
* @api private
*/
function regexpToFunction(re) {
return function(obj){
return re.test(obj);
};
}
/**
* Convert property `str` to a function.
*
* @param {String} str
* @return {Function}
* @api private
*/
function stringToFunction(str) {
// immediate such as "> 20"
if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str);
// properties such as "name.first" or "age > 18" or "age > 18 && age < 36"
return new Function('_', 'return ' + get(str));
}
/**
* Convert `object` to a function.
*
* @param {Object} object
* @return {Function}
* @api private
*/
function objectToFunction(obj) {
var match = {};
for (var key in obj) {
match[key] = typeof obj[key] === 'string'
? defaultToFunction(obj[key])
: toFunction(obj[key]);
}
return function(val){
if (typeof val !== 'object') return false;
for (var key in match) {
if (!(key in val)) return false;
if (!match[key](val[key])) return false;
}
return true;
};
}
/**
* Built the getter function. Supports getter style functions
*
* @param {String} str
* @return {String}
* @api private
*/
function get(str) {
var props = expr(str);
if (!props.length) return '_.' + str;
var val, i, prop;
for (i = 0; i < props.length; i++) {
prop = props[i];
val = '_.' + prop;
val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")";
// mimic negative lookbehind to avoid problems with nested properties
str = stripNested(prop, str, val);
}
return str;
}
/**
* Mimic negative lookbehind to avoid problems with nested properties.
*
* See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
*
* @param {String} prop
* @param {String} str
* @param {String} val
* @return {String}
* @api private
*/
function stripNested (prop, str, val) {
return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) {
return $1 ? $0 : val;
});
}
}, {"props":118,"component-props":118}],
173: [function(require, module, exports) {
/**
* Parse the given `url`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(url){
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
port: a.port,
hash: a.hash,
hostname: a.hostname,
pathname: a.pathname,
protocol: a.protocol,
search: a.search,
query: a.search.slice(1)
}
};
/**
* Check if `url` is absolute.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isAbsolute = function(url){
if (0 == url.indexOf('//')) return true;
if (~url.indexOf('://')) return true;
return false;
};
/**
* Check if `url` is relative.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isRelative = function(url){
return ! exports.isAbsolute(url);
};
/**
* Check if `url` is cross domain.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isCrossDomain = function(url){
url = exports.parse(url);
return url.hostname != location.hostname
|| url.port != location.port
|| url.protocol != location.protocol;
};
}, {}],
40: [function(require, module, exports) {
/**
* Module dependencies.
*/
var push = require('global-queue')('dataLayer', { wrap: false });
var integration = require('analytics.js-integration');
/**
* Expose `GTM`.
*/
var GTM = module.exports = integration('Google Tag Manager')
.assumesPageview()
.global('dataLayer')
.global('google_tag_manager')
.option('containerId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');
/**
* Initialize.
*
* https://developers.google.com/tag-manager
*
* @param {Object} page
*/
GTM.prototype.initialize = function(){
push({ 'gtm.start': +new Date, event: 'gtm.js' });
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
GTM.prototype.loaded = function(){
return !! (window.dataLayer && [].push != window.dataLayer.push);
};
/**
* Page.
*
* @param {Page} page
* @api public
*/
GTM.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
var track;
// all
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Track.
*
* https://developers.google.com/tag-manager/devguide#events
*
* @param {Track} track
* @api public
*/
GTM.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
push(props);
};
}, {"global-queue":158,"analytics.js-integration":88}],
41: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var Identify = require('facade').Identify;
var Track = require('facade').Track;
var callback = require('callback');
var load = require('load-script');
var onBody = require('on-body');
var each = require('each');
var is = require('is');
var pick = require('pick');
var omit = require('omit');
/**
* Expose `GoSquared` integration.
*/
var GoSquared = module.exports = integration('GoSquared')
.assumesPageview()
.global('_gs')
.option('siteToken', '')
.option('anonymizeIP', false)
.option('cookieDomain', null)
.option('useCookies', true)
.option('trackHash', false)
.option('trackLocal', false)
.option('trackParams', true)
.tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');
/**
* Initialize.
*
* https://www.gosquared.com/developer/tracker
* Options: https://www.gosquared.com/developer/tracker/configuration
*
* @param {Object} page
*/
GoSquared.prototype.initialize = function(page){
var self = this;
var options = this.options;
var user = this.analytics.user();
push(options.siteToken);
each(options, function(name, value){
if ('siteToken' == name) return;
if (null == value) return;
push('set', name, value);
});
self.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
self.load(this.ready);
};
/**
* Loaded? (checks if the tracker version is set)
*
* @return {Boolean}
*/
GoSquared.prototype.loaded = function(){
return !! (window._gs && window._gs.v);
};
/**
* Page.
*
* https://www.gosquared.com/docs/tracking/api/#pageviews
*
* @param {Page} page
*/
GoSquared.prototype.page = function(page){
var props = page.properties();
var name = page.fullName();
push('track', props.path, name || props.title)
};
/**
* Identify.
*
* https://www.gosquared.com/docs/tracking/identify
*
* @param {Identify} identify
*/
GoSquared.prototype.identify = function(identify){
var traits = identify.traits({
createdAt: 'created_at',
firstName: 'first_name',
lastName: 'last_name',
title: 'company_position',
industry: 'company_industry'
});
// https://www.gosquared.com/docs/tracking/api/#properties
var specialKeys = [
'id',
'email',
'name',
'first_name',
'last_name',
'username',
'description',
'avatar',
'phone',
'created_at',
'company_name',
'company_size',
'company_position',
'company_industry'
];
// Segment allows traits to all be in a flat object
// GoSquared requires all custom properties to be in a `custom` object,
// select all special keys
var props = pick.apply(null, [traits].concat(specialKeys));
props.custom = omit(specialKeys, traits);
var id = identify.userId();
if (id) {
push('identify', id, props);
} else {
push('properties', props);
}
var email = identify.email();
var username = identify.username();
var name = email || username || id;
if (name) push('set', 'visitorName', name);
};
/**
* Track.
*
* https://www.gosquared.com/docs/tracking/events
*
* @param {Track} track
*/
GoSquared.prototype.track = function(track){
push('event', track.event(), track.properties());
};
/**
* Checked out.
*
* https://www.gosquared.com/docs/tracking/ecommerce
*
* @param {Track} track
* @api private
*/
GoSquared.prototype.completedOrder = function(track){
var products = track.products();
var items = [];
each(products, function(product){
var track = new Track({ properties: product });
items.push({
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
});
})
push('transaction', track.orderId(), {
revenue: track.total(),
track: true
}, items);
};
/**
* Push to `_gs.q`.
*
* @param {...} args
* @api private
*/
function push(){
var _gs = window._gs = window._gs || function(){
(_gs.q = _gs.q || []).push(arguments);
};
_gs.apply(null, arguments);
}
}, {"analytics.js-integration":88,"facade":132,"callback":94,"load-script":128,"on-body":129,"each":4,"is":91,"pick":175,"omit":176}],
175: [function(require, module, exports) {
/**
* Expose `pick`.
*/
module.exports = pick;
/**
* Pick keys from an `obj`.
*
* @param {Object} obj
* @param {Strings} keys...
* @return {Object}
*/
function pick(obj){
var keys = [].slice.call(arguments, 1);
var ret = {};
for (var i = 0, key; key = keys[i]; i++) {
if (key in obj) ret[key] = obj[key];
}
return ret;
}
}, {}],
176: [function(require, module, exports) {
/**
* Expose `omit`.
*/
module.exports = omit;
/**
* Return a copy of the object without the specified keys.
*
* @param {Array} keys
* @param {Object} object
* @return {Object}
*/
function omit(keys, object){
var ret = {};
for (var item in object) {
ret[item] = object[item];
}
for (var i = 0; i < keys.length; i++) {
delete ret[keys[i]];
}
return ret;
}
}, {}],
42: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var alias = require('alias');
/**
* Expose `Heap` integration.
*/
var Heap = module.exports = integration('Heap')
.global('heap')
.option('appId', '')
.tag('<script src="//cdn.heapanalytics.com/js/heap-{{ appId }}.js">');
/**
* Initialize.
*
* https://heapanalytics.com/docs/installation#web
*
* @param {Object} page
*/
Heap.prototype.initialize = function(page){
window.heap = window.heap || [];
window.heap.load = function(appid, config){
window.heap.appid = appid;
window.heap.config = config;
var methodFactory = function(type){
return function(){
heap.push([type].concat(Array.prototype.slice.call(arguments, 0)));
};
};
var methods = ['clearEventProperties', 'identify', 'setEventProperties', 'track', 'unsetEventProperty'];
for (var i = 0; i < methods.length; i++) {
heap[methods[i]] = methodFactory(methods[i]);
}
};
window.heap.load(this.options.appId);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Heap.prototype.loaded = function(){
return (window.heap && window.heap.appid);
};
/**
* Identify.
*
* https://heapanalytics.com/docs#identify
*
* @param {Identify} identify
*/
Heap.prototype.identify = function(identify){
var traits = identify.traits({ email: '_email' });
var id = identify.userId();
if (id) traits.handle = id;
window.heap.identify(traits);
};
/**
* Track.
*
* https://heapanalytics.com/docs#track
*
* @param {Track} track
*/
Heap.prototype.track = function(track){
window.heap.track(track.event(), track.properties());
};
}, {"analytics.js-integration":88,"alias":162}],
43: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
/**
* Expose `hellobar.com` integration.
*/
var Hellobar = module.exports = integration('Hello Bar')
.assumesPageview()
.global('_hbq')
.option('apiKey', '')
.tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');
/**
* Initialize.
*
* https://s3.amazonaws.com/scripts.hellobar.com/bb900665a3090a79ee1db98c3af21ea174bbc09f.js
*
* @param {Object} page
*/
Hellobar.prototype.initialize = function(page){
window._hbq = window._hbq || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Hellobar.prototype.loaded = function(){
return !! (window._hbq && window._hbq.push !== Array.prototype.push);
};
}, {"analytics.js-integration":88}],
44: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var is = require('is');
/**
* Expose `HitTail` integration.
*/
var HitTail = module.exports = integration('HitTail')
.assumesPageview()
.global('htk')
.option('siteId', '')
.tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');
/**
* Initialize.
*
* @param {Object} page
*/
HitTail.prototype.initialize = function(page){
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
HitTail.prototype.loaded = function(){
return is.fn(window.htk);
};
}, {"analytics.js-integration":88,"is":91}],
45: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_hsq');
var convert = require('convert-dates');
/**
* Expose `HubSpot` integration.
*/
var HubSpot = module.exports = integration('HubSpot')
.assumesPageview()
.global('_hsq')
.option('portalId', null)
.tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');
/**
* Initialize.
*
* @param {Object} page
*/
HubSpot.prototype.initialize = function(page){
window._hsq = [];
var cache = Math.ceil(new Date() / 300000) * 300000;
this.load({ cache: cache }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
HubSpot.prototype.loaded = function(){
return !! (window._hsq && window._hsq.push !== Array.prototype.push);
};
/**
* Page.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
HubSpot.prototype.page = function(page){
push('_trackPageview');
};
/**
* Identify.
*
* @param {Identify} identify
*/
HubSpot.prototype.identify = function(identify){
if (!identify.email()) return;
var traits = identify.traits();
traits = convertDates(traits);
push('identify', traits);
};
/**
* Track.
*
* @param {Track} track
*/
HubSpot.prototype.track = function(track){
var props = track.properties();
props = convertDates(props);
push('trackEvent', track.event(), props);
};
/**
* Convert all the dates in the HubSpot properties to millisecond times
*
* @param {Object} properties
*/
function convertDates(properties){
return convert(properties, function(date){ return date.getTime(); });
}
}, {"analytics.js-integration":88,"global-queue":158,"convert-dates":163}],
46: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var alias = require('alias');
/**
* Expose `Improvely` integration.
*/
var Improvely = module.exports = integration('Improvely')
.assumesPageview()
.global('_improvely')
.global('improvely')
.option('domain', '')
.option('projectId', null)
.tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');
/**
* Initialize.
*
* http://www.improvely.com/docs/landing-page-code
*
* @param {Object} page
*/
Improvely.prototype.initialize = function(page){
window._improvely = [];
window.improvely = { init: function(e, t){ window._improvely.push(["init", e, t]); }, goal: function(e){ window._improvely.push(["goal", e]); }, label: function(e){ window._improvely.push(["label", e]); }};
var domain = this.options.domain;
var id = this.options.projectId;
window.improvely.init(domain, id);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Improvely.prototype.loaded = function(){
return !! (window.improvely && window.improvely.identify);
};
/**
* Identify.
*
* http://www.improvely.com/docs/labeling-visitors
*
* @param {Identify} identify
*/
Improvely.prototype.identify = function(identify){
var id = identify.userId();
if (id) window.improvely.label(id);
};
/**
* Track.
*
* http://www.improvely.com/docs/conversion-code
*
* @param {Track} track
*/
Improvely.prototype.track = function(track){
var props = track.properties({ revenue: 'amount' });
props.type = track.event();
window.improvely.goal(props);
};
}, {"analytics.js-integration":88,"alias":162}],
47: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_iva');
var Track = require('facade').Track;
var each = require('each');
var is = require('is');
/**
* HOP.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `InsideVault` integration.
*/
var InsideVault = module.exports = integration('InsideVault')
.global('_iva')
.option('clientId', '')
.option('domain', '')
.tag('<script src="//analytics.staticiv.com/iva.js">')
.mapping('events');
/**
* Initialize.
*
* @param page
*/
InsideVault.prototype.initialize = function(page){
var domain = this.options.domain;
window._iva = window._iva || [];
push('setClientId', this.options.clientId);
var userId = this.analytics.user().id();
if (userId) push('setUserId', userId);
if (domain) push('setDomain', domain);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
InsideVault.prototype.loaded = function(){
return !! (window._iva && window._iva.push !== Array.prototype.push);
};
/**
* Identify.
*
* @param {Identify} identify
*/
InsideVault.prototype.identify = function(identify){
push('setUserId', identify.userId());
};
/**
* Page.
*
* @param {Page} page
*/
InsideVault.prototype.page = function(page){
// they want every landing page to send a "click" event.
push('trackEvent', 'click');
};
/**
* Track.
*
* Tracks everything except 'sale' events.
*
* @param {Track} track
*/
InsideVault.prototype.track = function(track){
var user = this.analytics.user();
var events = this.events(track.event());
var value = track.revenue() || track.value() || 0;
var eventId = track.orderId() || user.id() || '';
each(events, function(event){
// 'sale' is a special event that will be routed to a table that is deprecated on InsideVault's end.
// They don't want a generic 'sale' event to go to their deprecated table.
if (event != 'sale') {
push('trackEvent', event, value, eventId);
}
});
};
}, {"analytics.js-integration":88,"global-queue":158,"facade":132,"each":4,"is":91}],
48: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('__insp');
var alias = require('alias');
var clone = require('clone');
/**
* Expose `Inspectlet` integration.
*/
var Inspectlet = module.exports = integration('Inspectlet')
.assumesPageview()
.global('__insp')
.global('__insp_')
.option('wid', '')
.tag('<script src="//cdn.inspectlet.com/inspectlet.js">');
/**
* Initialize.
*
* https://www.inspectlet.com/dashboard/embedcode/1492461759/initial
*
* @param {Object} page
*/
Inspectlet.prototype.initialize = function(page){
push('wid', this.options.wid);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Inspectlet.prototype.loaded = function(){
return !! (window.__insp_ && window.__insp);
};
/**
* Identify.
*
* http://www.inspectlet.com/docs#tagging
*
* @param {Identify} identify
*/
Inspectlet.prototype.identify = function(identify){
var traits = identify.traits({ id: 'userid' });
var email = identify.email();
if (email) push('identify', email);
push('tagSession', traits);
};
/**
* Track.
*
* http://www.inspectlet.com/docs/tags
*
* @param {Track} track
*/
Inspectlet.prototype.track = function(track){
push('tagSession', track.event());
};
/**
* Page.
*
* http://www.inspectlet.com/docs/tags
*
* @param {Track} track
*/
Inspectlet.prototype.page = function(){
push('virtualPage');
};
}, {"analytics.js-integration":88,"global-queue":158,"alias":162,"clone":95}],
49: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var convertDates = require('convert-dates');
var defaults = require('defaults');
var del = require('obj-case').del;
var isEmail = require('is-email');
var load = require('load-script');
var empty = require('is-empty');
var alias = require('alias');
var each = require('each');
var is = require('is');
/**
* Expose `Intercom` integration.
*/
var Intercom = module.exports = integration('Intercom')
.global('Intercom')
.option('activator', '#IntercomDefaultWidget')
.option('appId', '')
.tag('<script src="https://widget.intercom.io/widget/{{ appId }}">');
/**
* Initialize.
*
* http://docs.intercom.io/
* http://docs.intercom.io/#IntercomJS
*
* @param {Object} page
*/
Intercom.prototype.initialize = function(page){
initialize();
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Intercom.prototype.loaded = function(){
return is.fn(window.Intercom);
};
/**
* Page.
*
* @param {Page} page
*/
Intercom.prototype.page = function(){
this.bootOrUpdate();
};
/**
* Identify.
*
* http://docs.intercom.io/#IntercomJS
*
* @param {Identify} identify
*/
Intercom.prototype.identify = function(identify){
var traits = identify.traits({ userId: 'user_id' });
var opts = identify.options(this.name);
var companyCreated = identify.companyCreated();
var created = identify.created();
var email = identify.email();
var name = identify.name();
var id = identify.userId();
var group = this.analytics.group();
if (!id && !traits.email) {
return;
}
// intercom requires `company` to be an object. default it with group traits
// so that we guarantee an `id` is there, since they require it
if (traits.company !== null && !is.object(traits.company)) {
delete traits.company;
}
if (traits.company) {
defaults(traits.company, group.traits());
}
// name
if (name) traits.name = name;
// handle dates
if (created) {
del(traits, 'created');
del(traits, 'createdAt');
traits.created_at = created;
}
if (companyCreated) {
del(traits.company, 'created');
del(traits.company, 'createdAt');
traits.company.created_at = companyCreated;
}
// convert dates
traits = convertDates(traits, formatDate);
// handle options
if (opts.increments) traits.increments = opts.increments;
if (opts.userHash) traits.user_hash = opts.userHash;
if (opts.user_hash) traits.user_hash = opts.user_hash;
this.bootOrUpdate(traits);
};
/**
* Group.
*
* @param {Group} group
*/
Intercom.prototype.group = function(group){
var props = group.properties();
props = alias(props, { createdAt: 'created' });
props = alias(props, { created: 'created_at' });
var id = group.groupId();
if (id) props.id = id;
api('update', { company: props });
};
/**
* Track.
*
* @param {Track} track
*/
Intercom.prototype.track = function(track){
api('trackEvent', track.event(), track.properties());
};
/**
* Boots or updates, as appropriate.
*
* @param {Object} options
*/
Intercom.prototype.bootOrUpdate = function(options){
options = options || {};
var method = this.booted === true ? 'update' : 'boot';
var activator = this.options.activator;
options.app_id = this.options.appId;
// Intercom, will force the widget to appear
// if the selector is #IntercomDefaultWidget
// so no need to check inbox, just need to check
// that the selector isn't #IntercomDefaultWidget.
if (activator !== '#IntercomDefaultWidget') {
options.widget = { activator: activator };
}
api(method, options);
this.booted = true;
};
/**
* Format a date to Intercom's liking.
*
* @param {Date} date
* @return {Number}
*/
function formatDate(date){
return Math.floor(date / 1000);
}
/**
* Initialize the Intercom call queue.
*/
function initialize(){
window.Intercom = function(){
window.Intercom.q.push(arguments);
};
window.Intercom.q = [];
}
/**
* Push a call onto the queue.
*/
function api(){
window.Intercom.apply(window.Intercom, arguments);
}
}, {"analytics.js-integration":88,"convert-dates":163,"defaults":157,"obj-case":92,"is-email":154,"load-script":128,"is-empty":122,"alias":162,"each":4,"is":91}],
50: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var clone = require('clone');
/**
* Expose `Keen IO` integration.
*/
var Keen = module.exports = integration('Keen IO')
.global('Keen')
.option('projectId', '')
.option('readKey', '')
.option('writeKey', '')
.option('ipAddon', false)
.option('uaAddon', false)
.option('urlAddon', false)
.option('referrerAddon', false)
.option('trackNamedPages', true)
.option('trackAllPages', false)
.option('trackCategorizedPages', true)
.tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">');
/**
* Initialize.
*
* https://keen.io/docs/
*/
Keen.prototype.initialize = function(){
var options = this.options;
!(function(a,b){
if (void 0===b[a]){
b["_"+a]={},
b[a]=function(c){
b["_"+a].clients=b["_"+a].clients||{},
b["_"+a].clients[c.projectId]=this,
this._config=c
},
b[a].ready=function(c){
b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)
};
for (var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){
var e=c[d],
f=function(a){
return function(){
return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this
}
};
b[a].prototype[e]=f(e)
}
}
})("Keen",window);
this.client = new window.Keen({
projectId: options.projectId,
writeKey: options.writeKey,
readKey: options.readKey
});
// if you have a read-key, then load the full keen library
var lib = this.options.readKey ? 'keen' : 'keen-tracker';
this.load({ lib: lib }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Keen.prototype.loaded = function(){
return !!(window.Keen && window.Keen.prototype.configure);
};
/**
* Page.
*
* @param {Page} page
*/
Keen.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* TODO: migrate from old `userId` to simpler `id`
* https://keen.io/docs/data-collection/data-enrichment/#add-ons
*
* Set up the Keen addons object. These must be specifically
* enabled by the settings in order to include the plugins, or else
* Keen will reject the request.
*
* @param {Identify} identify
*/
Keen.prototype.identify = function(identify){
var traits = identify.traits();
var id = identify.userId();
var user = {};
if (id) user.userId = id;
if (traits) user.traits = traits;
var props = { user: user };
this.addons(props, identify);
this.client.setGlobalProperties(function(){
return clone(props);
});
};
/**
* Track.
*
* @param {Track} track
*/
Keen.prototype.track = function(track){
var props = track.properties();
this.addons(props, track);
this.client.addEvent(track.event(), props);
};
/**
* Attach addons to `obj` with `msg`.
*
* @param {Object} obj
* @param {Facade} msg
*/
Keen.prototype.addons = function(obj, msg){
var options = this.options;
var addons = [];
if (options.ipAddon) {
addons.push({
name: 'keen:ip_to_geo',
input: { ip: 'ip_address' },
output: 'ip_geo_info'
});
obj.ip_address = '${keen.ip}';
}
if (options.uaAddon) {
addons.push({
name: 'keen:ua_parser',
input: { ua_string: 'user_agent' },
output: 'parsed_user_agent'
});
obj.user_agent = '${keen.user_agent}';
}
if (options.urlAddon) {
addons.push({
name: 'keen:url_parser',
input: { url: 'page_url' },
output: 'parsed_page_url'
});
obj.page_url = document.location.href;
}
if (options.referrerAddon) {
addons.push({
name: 'keen:referrer_parser',
input: {
referrer_url: 'referrer_url',
page_url: 'page_url'
},
output: 'referrer_info'
});
obj.referrer_url = document.referrer;
obj.page_url = document.location.href;
}
obj.keen = {
timestamp: msg.timestamp(),
addons: addons
};
};
}, {"analytics.js-integration":88,"clone":95}],
51: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var indexof = require('indexof');
var is = require('is');
/**
* Expose `Kenshoo` integration.
*/
var Kenshoo = module.exports = integration('Kenshoo')
.global('k_trackevent')
.option('cid', '')
.option('subdomain', '')
.option('events', [])
.tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');
/**
* Initialize.
*
* See https://gist.github.com/justinboyle/7875832
*
* @param {Object} page
*/
Kenshoo.prototype.initialize = function(page){
this.load(this.ready);
};
/**
* Loaded? (checks if the tracking function is set)
*
* @return {Boolean}
*/
Kenshoo.prototype.loaded = function(){
return is.fn(window.k_trackevent);
};
/**
* Track.
*
* Only tracks events if they are listed in the events array option.
* We've asked for docs a few times but no go :/
*
* https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb
*
* @param {Track} event
*/
Kenshoo.prototype.track = function(track){
var events = this.options.events;
var traits = track.traits();
var event = track.event();
var revenue = track.revenue() || 0;
if (!~indexof(events, event)) return;
var params = [
'id=' + this.options.cid,
'type=conv',
'val=' + revenue,
'orderId=' + track.orderId(),
'promoCode=' + track.coupon(),
'valueCurrency=' + track.currency(),
// Live tracking fields. Ignored for now (until we get documentation).
'GCID=',
'kw=',
'product='
];
window.k_trackevent(params, this.options.subdomain);
};
}, {"analytics.js-integration":88,"indexof":116,"is":91}],
52: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_kmq');
var Track = require('facade').Track;
var alias = require('alias');
var each = require('each');
var is = require('is');
/**
* Expose `KISSmetrics` integration.
*/
var KISSmetrics = module.exports = integration('KISSmetrics')
.assumesPageview()
.global('_kmq')
.global('KM')
.global('_kmil')
.option('apiKey', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('prefixProperties', true)
.tag('library', '<script src="//scripts.kissmetrics.com/{{ apiKey }}.2.js">');
/**
* Check if browser is mobile, for kissmetrics.
*
* http://support.kissmetrics.com/how-tos/browser-detection.html#mobile-vs-non-mobile
*/
exports.isMobile = navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/iPhone|iPod/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/Opera Mini/i)
|| navigator.userAgent.match(/IEMobile/i);
/**
* Initialize.
*
* http://support.kissmetrics.com/apis/javascript
*
* @param {Object} page
*/
KISSmetrics.prototype.initialize = function(page){
var self = this;
window._kmq = [];
if (exports.isMobile) push('set', { 'Mobile Session': 'Yes' });
this.load('library', function(){
self.trackPage(page);
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
KISSmetrics.prototype.loaded = function(){
return is.object(window.KM);
};
/**
* Page.
*
* @param {Page} page
*/
KISSmetrics.prototype.page = function(page){
if (!window.KM_SKIP_PAGE_VIEW) window.KM.pageView();
this.trackPage(page);
};
/**
* Track page.
*
* @param {Page} page
*/
KISSmetrics.prototype.trackPage = function(page){
var category = page.category();
var name = page.fullName();
var opts = this.options;
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* @param {Identify} identify
*/
KISSmetrics.prototype.identify = function(identify){
var traits = identify.traits();
var id = identify.userId();
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {Track} track
*/
KISSmetrics.prototype.track = function(track){
var mapping = { revenue: 'Billing Amount' };
var event = track.event();
var properties = track.properties(mapping);
if (this.options.prefixProperties) properties = prefix(event, properties);
push('record', event, properties);
};
/**
* Alias.
*
* @param {Alias} to
*/
KISSmetrics.prototype.alias = function(alias){
push('alias', alias.to(), alias.from());
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
KISSmetrics.prototype.completedOrder = function(track){
var products = track.products();
var event = track.event();
// transaction
push('record', event, prefix(event, track.properties()));
// items
window._kmq.push(function(){
var km = window.KM;
each(products, function(product, i){
var item = prefix(event, product);
item._t = km.ts() + i;
item._d = 1;
km.set(item);
});
});
};
/**
* Prefix properties with the event name.
*
* @param {String} event
* @param {Object} properties
* @return {Object} prefixed
* @api private
*/
function prefix(event, properties){
var prefixed = {};
each(properties, function(key, val){
if (key === 'Billing Amount') {
prefixed[key] = val;
} else {
prefixed[event + ' - ' + key] = val;
}
});
return prefixed;
}
}, {"analytics.js-integration":88,"global-queue":158,"facade":132,"alias":162,"each":4,"is":91}],
53: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_learnq');
var tick = require('next-tick');
var alias = require('alias');
/**
* Trait aliases.
*/
var aliases = {
id: '$id',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
phone: '$phone_number',
title: '$title'
};
/**
* Expose `Klaviyo` integration.
*/
var Klaviyo = module.exports = integration('Klaviyo')
.assumesPageview()
.global('_learnq')
.option('apiKey', '')
.tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');
/**
* Initialize.
*
* https://www.klaviyo.com/docs/getting-started
*
* @param {Object} page
*/
Klaviyo.prototype.initialize = function(page){
var self = this;
push('account', this.options.apiKey);
this.load(function(){
tick(self.ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Klaviyo.prototype.loaded = function(){
return !! (window._learnq && window._learnq.push !== Array.prototype.push);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Klaviyo.prototype.identify = function(identify){
var traits = identify.traits(aliases);
if (!traits.$id && !traits.$email) return;
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
Klaviyo.prototype.group = function(group){
var props = group.properties();
if (!props.name) return;
push('identify', { $organization: props.name });
};
/**
* Track.
*
* @param {Track} track
*/
Klaviyo.prototype.track = function(track){
push('track', track.event(), track.properties({
revenue: '$value'
}));
};
}, {"analytics.js-integration":88,"global-queue":158,"next-tick":103,"alias":162}],
54: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var clone = require('clone');
var each = require('each');
var Identify = require('facade').Identify;
var when = require('when');
var tick = require('next-tick');
/**
* Expose `LiveChat` integration.
*/
var LiveChat = module.exports = integration('LiveChat')
.assumesPageview()
.global('__lc')
.global('__lc_inited')
.global('LC_API')
.global('LC_Invite')
.option('group', 0)
.option('license', '')
.option('listen', false)
.tag('<script src="//cdn.livechatinc.com/tracking.js">');
/**
* The context for this integration.
*/
var integration = {
name: 'livechat',
version: '1.0.0'
};
/**
* Initialize.
*
* http://www.livechatinc.com/api/javascript-api
*
* @param {Object} page
*/
LiveChat.prototype.initialize = function(page){
var self = this;
var user = this.analytics.user();
var identify = new Identify({
userId: user.id(),
traits: user.traits()
});
window.__lc = clone(this.options);
window.__lc.visitor = {
name: identify.name(),
email: identify.email()
};
// listen is not an option we need from clone
delete window.__lc.listen;
this.load(function(){
when(function(){
return self.loaded();
}, function(){
if (self.options.listen) self.attachListeners();
tick(self.ready);
});
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
LiveChat.prototype.loaded = function(){
return !!(window.LC_API && window.LC_Invite);
};
/**
* Listen for chat events.
*/
LiveChat.prototype.attachListeners = function(){
var self = this;
window.LC_API = window.LC_API || {};
window.LC_API.on_chat_started = function(data){
self.analytics.track(
'Live Chat Conversation Started',
{ agentName: data.agent_name },
{ context: { integration: integration }
});
};
window.LC_API.on_message = function(data){
if (data.user_type === 'visitor') {
self.analytics.track(
'Live Chat Message Sent',
{},
{ context: { integration: integration }
});
} else {
self.analytics.track(
'Live Chat Message Received',
{ agentName: data.agent_name, agentUsername: data.agent_login },
{ context: { integration: integration }
});
}
};
window.LC_API.on_chat_ended = function(){
self.analytics.track('Live Chat Conversation Ended');
};
};
/**
* Identify.
*
* @param {Identify} identify
*/
LiveChat.prototype.identify = function(identify){
var traits = identify.traits({ userId: 'User ID' });
window.LC_API.set_custom_variables(convert(traits));
};
/**
* Convert a traits object into the format LiveChat requires.
*
* @param {Object} traits
* @return {Array}
*/
function convert(traits){
var arr = [];
each(traits, function(key, value){
arr.push({ name: key, value: value });
});
return arr;
}
}, {"analytics.js-integration":88,"clone":95,"each":4,"facade":132,"when":131,"next-tick":103}],
55: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var Identify = require('facade').Identify;
var useHttps = require('use-https');
/**
* Expose `LuckyOrange` integration.
*/
var LuckyOrange = module.exports = integration('Lucky Orange')
.assumesPageview()
.global('_loq')
.global('__wtw_watcher_added')
.global('__wtw_lucky_site_id')
.global('__wtw_lucky_is_segment_io')
.global('__wtw_custom_user_data')
.option('siteId', null)
.tag('http', '<script src="http://www.luckyorange.com/w.js?{{ cache }}">')
.tag('https', '<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');
/**
* Initialize.
*
* @param {Object} page
*/
LuckyOrange.prototype.initialize = function(page){
var user = this.analytics.user();
window._loq || (window._loq = []);
window.__wtw_lucky_site_id = this.options.siteId;
this.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
var cache = Math.floor(new Date().getTime() / 60000);
var name = useHttps() ? 'https' : 'http';
this.load(name, { cache: cache }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
LuckyOrange.prototype.loaded = function(){
return !! window.__wtw_watcher_added;
};
/**
* Identify.
*
* @param {Identify} identify
*/
LuckyOrange.prototype.identify = function(identify){
var traits = identify.traits();
var email = identify.email();
var name = identify.name();
if (name) traits.name = name;
if (email) traits.email = email;
window.__wtw_custom_user_data = traits;
};
}, {"analytics.js-integration":88,"facade":132,"use-https":90}],
56: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var alias = require('alias');
/**
* Expose `Lytics` integration.
*/
var Lytics = module.exports = integration('Lytics')
.global('jstag')
.option('cid', '')
.option('cookie', 'seerid')
.option('delay', 2000)
.option('sessionTimeout', 1800)
.option('url', '//c.lytics.io')
.tag('<script src="//c.lytics.io/static/io.min.js">');
/**
* Options aliases.
*/
var aliases = {
sessionTimeout: 'sessecs'
};
/**
* Initialize.
*
* http://admin.lytics.io/doc#jstag
*
* @param {Object} page
*/
Lytics.prototype.initialize = function(page){
var options = alias(this.options, aliases);
window.jstag = (function(){var t = { _q: [], _c: options, ts: (new Date()).getTime() }; t.send = function(){this._q.push(['ready', 'send', Array.prototype.slice.call(arguments)]); return this; }; return t; })();
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Lytics.prototype.loaded = function(){
return !! (window.jstag && window.jstag.bind);
};
/**
* Page.
*
* @param {Page} page
*/
Lytics.prototype.page = function(page){
window.jstag.send(page.properties());
};
/**
* Idenfity.
*
* @param {Identify} identify
*/
Lytics.prototype.identify = function(identify){
var traits = identify.traits({ userId: '_uid' });
window.jstag.send(traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Lytics.prototype.track = function(track){
var props = track.properties();
props._e = track.event();
window.jstag.send(props);
};
}, {"analytics.js-integration":88,"alias":162}],
57: [function(require, module, exports) {
/**
* Module dependencies.
*/
var alias = require('alias');
var clone = require('clone');
var dates = require('convert-dates');
var integration = require('analytics.js-integration');
var is = require('is');
var iso = require('to-iso-string');
var indexof = require('indexof');
var del = require('obj-case').del;
var some = require('some');
/**
* Expose `Mixpanel` integration.
*/
var Mixpanel = module.exports = integration('Mixpanel')
.global('mixpanel')
.option('increments', [])
.option('cookieName', '')
.option('crossSubdomainCookie', false)
.option('secureCookie', false)
.option('nameTag', true)
.option('pageview', false)
.option('people', false)
.option('token', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js">');
/**
* Options aliases.
*/
var optionsAliases = {
cookieName: 'cookie_name',
crossSubdomainCookie: 'cross_subdomain_cookie',
secureCookie: 'secure_cookie'
};
/**
* Initialize.
*
* https://mixpanel.com/help/reference/javascript#installing
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init
*/
Mixpanel.prototype.initialize = function(){
(function(c, a){window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function(b, c, f){function d(a, b){var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function(){a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []);
this.options.increments = lowercase(this.options.increments);
var options = alias(this.options, optionsAliases);
window.mixpanel.init(options.token, options);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mixpanel.prototype.loaded = function(){
return !! (window.mixpanel && window.mixpanel.config);
};
/**
* Page.
*
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Mixpanel.prototype.page = function(page){
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Trait aliases.
*/
var traitAliases = {
created: '$created',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
lastSeen: '$last_seen',
name: '$name',
username: '$username',
phone: '$phone'
};
/**
* Identify.
*
* https://mixpanel.com/help/reference/javascript#super-properties
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript#storing-user-profiles
*
* @param {Identify} identify
*/
Mixpanel.prototype.identify = function(identify){
var username = identify.username();
var email = identify.email();
var id = identify.userId();
// id
if (id) window.mixpanel.identify(id);
// name tag
var nametag = email || username || id;
if (nametag) window.mixpanel.name_tag(nametag);
// traits
var traits = identify.traits(traitAliases);
if (traits.$created) del(traits, 'createdAt');
window.mixpanel.register(dates(traits, iso));
if (this.options.people) window.mixpanel.people.set(traits);
};
/**
* Track.
*
* https://mixpanel.com/help/reference/javascript#sending-events
* https://mixpanel.com/help/reference/javascript#tracking-revenue
*
* @param {Track} track
*/
Mixpanel.prototype.track = function(track){
var increments = this.options.increments;
var increment = track.event().toLowerCase();
var people = this.options.people;
var props = track.properties();
var revenue = track.revenue();
// delete mixpanel's reserved properties, so they don't conflict
delete props.distinct_id;
delete props.ip;
delete props.mp_name_tag;
delete props.mp_note;
delete props.token;
// convert arrays of objects to length, since mixpanel doesn't support object arrays
for (var key in props) {
var val = props[key];
if (is.array(val) && some(val, is.object)) props[key] = val.length;
}
// increment properties in mixpanel people
if (people && ~indexof(increments, increment)) {
window.mixpanel.people.increment(track.event());
window.mixpanel.people.set('Last ' + track.event(), new Date);
}
// track the event
props = dates(props, iso);
window.mixpanel.track(track.event(), props);
// track revenue specifically
if (revenue && people) {
window.mixpanel.people.track_charge(revenue);
}
};
/**
* Alias.
*
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias
*
* @param {Alias} alias
*/
Mixpanel.prototype.alias = function(alias){
var mp = window.mixpanel;
var to = alias.to();
if (mp.get_distinct_id && mp.get_distinct_id() === to) return;
// HACK: internal mixpanel API to ensure we don't overwrite
if (mp.get_property && mp.get_property('$people_distinct_id') === to) return;
// although undocumented, mixpanel takes an optional original id
mp.alias(to, alias.from());
};
/**
* Lowercase the given `arr`.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
function lowercase(arr){
var ret = new Array(arr.length);
for (var i = 0; i < arr.length; ++i) {
ret[i] = String(arr[i]).toLowerCase();
}
return ret;
}
}, {"alias":162,"clone":95,"convert-dates":163,"analytics.js-integration":88,"is":91,"to-iso-string":161,"indexof":116,"obj-case":92,"some":177}],
177: [function(require, module, exports) {
/**
* some
*/
var some = [].some;
/**
* test whether some elements in
* the array pass the test implemented
* by `fn`.
*
* example:
*
* some([1, 'foo', 'bar'], function (el, i) {
* return 'string' == typeof el;
* });
* // > true
*
* @param {Array} arr
* @param {Function} fn
* @return {bool}
*/
module.exports = function (arr, fn) {
if (some) return some.call(arr, fn);
for (var i = 0, l = arr.length; i < l; ++i) {
if (fn(arr[i], i)) return true;
}
return false;
};
}, {}],
58: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var bind = require('bind');
var when = require('when');
var is = require('is');
/**
* Expose `Mojn`
*/
var Mojn = module.exports = integration('Mojn')
.option('customerCode', '')
.global('_mojnTrack')
.tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Mojn.prototype.initialize = function(){
window._mojnTrack = window._mojnTrack || [];
window._mojnTrack.push({ cid: this.options.customerCode });
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load(function(){
when(loaded, ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mojn.prototype.loaded = function(){
return is.object(window._mojnTrack);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Mojn.prototype.identify = function(identify){
var email = identify.email();
if (!email) return;
var img = new Image();
img.src = '//matcher.idtargeting.com/identify.gif?cid=' + this.options.customerCode + '&_mjnctid='+email;
img.width = 1;
img.height = 1;
return img;
};
/**
* Track.
*
* @param {Track} event
*/
Mojn.prototype.track = function(track){
var properties = track.properties();
var revenue = properties.revenue;
var currency = properties.currency || '';
var conv = currency + revenue;
if (!revenue) return;
window._mojnTrack.push({ conv: conv });
return conv;
};
}, {"analytics.js-integration":88,"bind":101,"when":131,"is":91}],
59: [function(require, module, exports) {
/**
* Module dependencies.
*/
var push = require('global-queue')('_mfq');
var integration = require('analytics.js-integration');
var each = require('each');
/**
* Expose `Mouseflow`.
*/
var Mouseflow = module.exports = integration('Mouseflow')
.assumesPageview()
.global('mouseflow')
.global('_mfq')
.option('apiKey', '')
.option('mouseflowHtmlDelay', 0)
.tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');
/**
* Initalize.
*
* @param {Object} page
*/
Mouseflow.prototype.initialize = function(page){
window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay;
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mouseflow.prototype.loaded = function(){
return !! window.mouseflow;
};
/**
* Page.
*
* http://mouseflow.zendesk.com/entries/22528817-Single-page-websites
*
* @param {Page} page
*/
Mouseflow.prototype.page = function(page){
if (!window.mouseflow) return;
if ('function' != typeof mouseflow.newPageView) return;
mouseflow.newPageView();
};
/**
* Identify.
*
* http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Identify} identify
*/
Mouseflow.prototype.identify = function(identify){
set(identify.traits());
};
/**
* Track.
*
* http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Track} track
*/
Mouseflow.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
set(props);
};
/**
* Push each key and value in the given `obj` onto the queue.
*
* @param {Object} obj
*/
function set(obj){
each(obj, function(key, value){
push('setVariable', key, value);
});
}
}, {"global-queue":158,"analytics.js-integration":88,"each":4}],
60: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var useHttps = require('use-https');
var each = require('each');
var is = require('is');
/**
* Expose `MouseStats` integration.
*/
var MouseStats = module.exports = integration('MouseStats')
.assumesPageview()
.global('msaa')
.global('MouseStatsVisitorPlaybacks')
.option('accountNumber', '')
.tag('http', '<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">')
.tag('https', '<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');
/**
* Initialize.
*
* http://www.mousestats.com/docs/pages/allpages
*
* @param {Object} page
*/
MouseStats.prototype.initialize = function(page){
var number = this.options.accountNumber;
var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number;
var cache = Math.floor(new Date().getTime() / 60000);
var name = useHttps() ? 'https' : 'http';
this.load(name, { path: path, cache: cache }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
MouseStats.prototype.loaded = function(){
return is.array(window.MouseStatsVisitorPlaybacks);
};
/**
* Identify.
*
* http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks
*
* @param {Identify} identify
*/
MouseStats.prototype.identify = function(identify){
each(identify.traits(), function(key, value){
window.MouseStatsVisitorPlaybacks.customVariable(key, value);
});
};
}, {"analytics.js-integration":88,"use-https":90,"each":4,"is":91}],
61: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('__nls');
/**
* Expose `Navilytics` integration.
*/
var Navilytics = module.exports = integration('Navilytics')
.assumesPageview()
.global('__nls')
.option('memberId', '')
.option('projectId', '')
.tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');
/**
* Initialize.
*
* https://www.navilytics.com/member/code_settings
*
* @param {Object} page
*/
Navilytics.prototype.initialize = function(page){
window.__nls = window.__nls || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Navilytics.prototype.loaded = function(){
return !! (window.__nls && [].push != window.__nls.push);
};
/**
* Track.
*
* https://www.navilytics.com/docs#tags
*
* @param {Track} track
*/
Navilytics.prototype.track = function(track){
push('tagRecording', track.event());
};
}, {"analytics.js-integration":88,"global-queue":158}],
62: [function(require, module, exports) {
var integration = require('analytics.js-integration');
var alias = require('alias');
var Identify = require('facade').Identify;
/**
* Expose `plugin`.
*/
/*module.exports = exports = function(analytics){
analytics.addIntegration(Nudgespot);
};*/
/**
* Expose `Nudgespot` integration.
*/
var Nudgespot = module.exports = integration('Nudgespot')
.assumesPageview()
.option('apiKey', '')
.global('nudgespot')
.tag('<script id="nudgespot" src="//cdn.nudgespot.com/nudgespot.js">');
/**
* Initialize Nudgespot.
*/
Nudgespot.prototype.initialize = function(page){
window.nudgespot = window.nudgespot || [];
window.nudgespot.init = function(n, t){function f(n,m){var a=m.split('.');2==a.length&&(n=n[a[0]],m=a[1]);n[m]=function(){n.push([m].concat(Array.prototype.slice.call(arguments,0)))}}n._version=0.1;n._globals=[t];n.people=n.people||[];n.params=n.params||[];m="track register unregister identify set_config people.delete people.create people.update people.create_property people.tag people.remove_Tag".split(" ");for (var i=0;i<m.length;i++)f(n,m[i])};
window.nudgespot.init(window.nudgespot, this.options.apiKey);
this.load(this.ready);
};
/**
* Has the Nudgespot library been loaded yet?
*/
Nudgespot.prototype.loaded = function(){
return (!! window.nudgespot) && (window.nudgespot.push !== Array.prototype.push);
};
/**
* Identify a user.
*/
Nudgespot.prototype.identify = function(identify){
if (!identify.userId()) return this.debug('user id required');
var traits = identify.traits({ createdAt: 'created' });
traits = alias(traits, { created: 'created_at' });
window.nudgespot.identify(identify.userId(), traits);
};
/**
* Track an event.
*/
Nudgespot.prototype.track = function(track){
var properties = track.properties();
window.nudgespot.track(track.event(), properties);
};
}, {"analytics.js-integration":88,"alias":162,"facade":132}],
63: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var https = require('use-https');
var tick = require('next-tick');
/**
* Expose `Olark` integration.
*/
var Olark = module.exports = integration('Olark')
.assumesPageview()
.global('olark')
.option('identify', true)
.option('page', true)
.option('siteId', '')
.option('groupId', '')
.option('listen', false)
.option('track', false);
/**
* The context for this integration.
*/
var integration = {
name: 'olark',
version: '1.0.0'
};
/**
* Initialize.
*
* http://www.olark.com/documentation
* https://www.olark.com/documentation/javascript/api.chat.setOperatorGroup
*
* @param {Facade} page
*/
Olark.prototype.initialize = function(page){
var self = this;
this.load(function(){
tick(self.ready);
});
// assign chat to a specific site
var groupId = this.options.groupId;
if (groupId) api('chat.setOperatorGroup', { group: groupId });
// keep track of the widget's open state
api('box.onExpand', function(){ self._open = true; });
api('box.onShrink', function(){ self._open = false; });
// record events
if (this.options.listen) this.attachListeners();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Olark.prototype.loaded = function(){
return !! window.olark;
};
/**
* Listen for events.
*/
Olark.prototype.attachListeners = function(){
var self = this;
api('chat.onBeginConversation', function(){
self.analytics.track(
'Live Chat Conversation Started',
{},
{ context: { integration: integration }}
);
});
api('chat.onMessageToOperator', function(event){
self.analytics.track(
'Live Chat Message Sent',
{},
{ context: { integration: integration }}
);
});
api('chat.onMessageToVisitor', function(event){
self.analytics.track(
'Live Chat Message Received',
{},
{ context: { integration: integration }}
);
});
};
/**
* Load.
*
* @param {Function} callback
*/
Olark.prototype.load = function(callback){
var el = document.getElementById('olark');
window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while (q--) {(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={ 0:+new Date() };a.P=function(u){a.p[u]=new Date()-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return ["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if (!m) {return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if (/MSIE[ ]+6/.test(navigator.userAgent)) {b.src="javascript:false"}b.allowTransparency="true";v[j](b);try {b.contentWindow[g].open()}catch (w) {c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try {var t=b.contentWindow[g];t.write(p());t.close()}catch (x) {b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({ loader: "static.olark.com/jsclient/loader0.js", name:"olark", methods:["configure","extend","declare","identify"] });
window.olark.identify(this.options.siteId);
callback();
};
/**
* Page.
*
* @param {Facade} page
*/
Olark.prototype.page = function(page){
if (!this.options.page) return;
var props = page.properties();
var name = page.fullName();
if (!name && !props.url) return;
name = name ? name + ' page' : props.url;
this.notify('looking at ' + name);
};
/**
* Identify.
*
* @param {Facade} identify
*/
Olark.prototype.identify = function(identify){
if (!this.options.identify) return;
var username = identify.username();
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
var phone = identify.phone();
var name = identify.name() || identify.firstName();
if (traits) api('visitor.updateCustomFields', traits);
if (email) api('visitor.updateEmailAddress', { emailAddress: email });
if (phone) api('visitor.updatePhoneNumber', { phoneNumber: phone });
if (name) api('visitor.updateFullName', { fullName: name });
// figure out best nickname
var nickname = name || email || username || id;
if (name && email) nickname += ' (' + email + ')';
if (nickname) api('chat.updateVisitorNickname', { snippet: nickname });
};
/**
* Track.
*
* @param {Facade} track
*/
Olark.prototype.track = function(track){
if (!this.options.track) return;
this.notify('visitor triggered "' + track.event() + '"');
};
/**
* Send a notification `message` to the operator, only when a chat is active and
* when the chat is open.
*
* @param {String} message
*/
Olark.prototype.notify = function(message){
if (!this._open) return;
// lowercase since olark does
message = message.toLowerCase();
api('visitor.getDetails', function(data){
if (!data || !data.isConversing) return;
api('chat.sendNotificationToOperator', { body: message });
});
};
/**
* Helper for Olark API calls.
*
* @param {String} action
* @param {Object} value
*/
function api(action, value) {
window.olark('api.' + action, value);
}
}, {"analytics.js-integration":88,"use-https":90,"next-tick":103}],
64: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('optimizely');
var callback = require('callback');
var tick = require('next-tick');
var bind = require('bind');
var each = require('each');
/**
* Expose `Optimizely` integration.
*/
var Optimizely = module.exports = integration('Optimizely')
.option('variations', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://www.optimizely.com/docs/api#function-calls
*/
Optimizely.prototype.initialize = function(){
if (this.options.variations) {
var self = this;
tick(function(){
self.replay();
});
}
this.ready();
};
/**
* Track.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Track} track
*/
Optimizely.prototype.track = function(track){
var props = track.properties();
if (props.revenue) props.revenue *= 100;
push('trackEvent', track.event(), props);
};
/**
* Page.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Page} page
*/
Optimizely.prototype.page = function(page){
var category = page.category();
var name = page.fullName();
var opts = this.options;
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Replay experiment data as traits to other enabled providers.
*
* https://www.optimizely.com/docs/api#data-object
*/
Optimizely.prototype.replay = function(){
if (!window.optimizely) return; // in case the snippet isnt on the page
var data = window.optimizely.data;
if (!data || !data.experiments || !data.state) return;
var experiments = data.experiments;
var map = data.state.variationNamesMap;
var traits = {};
each(map, function(experimentId, variation){
var experiment = experiments[experimentId].name;
traits['Experiment: ' + experiment] = variation;
});
this.analytics.identify(traits);
};
}, {"analytics.js-integration":88,"global-queue":158,"callback":94,"next-tick":103,"bind":101,"each":4}],
65: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_pq');
/**
* Expose `PerfectAudience` integration.
*/
var PerfectAudience = module.exports = integration('Perfect Audience')
.assumesPageview()
.global('_pq')
.option('siteId', '')
.tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');
/**
* Initialize.
*
* http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api
*
* @param {Object} page
*/
PerfectAudience.prototype.initialize = function(page){
window._pq = window._pq || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
PerfectAudience.prototype.loaded = function(){
return !! (window._pq && window._pq.push);
};
/**
* Track.
*
* http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api
*
* @param {Track} event
*/
PerfectAudience.prototype.track = function(track){
var total = track.total() || track.revenue();
var orderId = track.orderId();
var props = {};
var sendProps = false;
if (total) {
props.revenue = total;
sendProps = true;
}
if (orderId) {
props.orderId = orderId;
sendProps = true;
}
if (!sendProps) return push('track', track.event());
return push('track', track.event(), props);
};
/**
* Viewed Product.
*
* http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api
*
* @param {Track} event
*/
PerfectAudience.prototype.viewedProduct = function(track){
var product = track.id() || track.sku();
push('track', track.event());
push('trackProduct', product);
};
/**
* Completed Purchase.
*
* http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api
*
* @param {Track} event
*/
PerfectAudience.prototype.completedOrder = function(track){
var total = track.total() || track.revenue();
var orderId = track.orderId();
var props = {};
if (total) props.revenue = total;
if (orderId) props.orderId = orderId;
push('track', track.event(), props);
};
}, {"analytics.js-integration":88,"global-queue":158}],
66: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_prum');
var date = require('load-date');
/**
* Expose `Pingdom` integration.
*/
var Pingdom = module.exports = integration('Pingdom')
.assumesPageview()
.global('_prum')
.global('PRUM_EPISODES')
.option('id', '')
.tag('<script src="//rum-static.pingdom.net/prum.min.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Pingdom.prototype.initialize = function(page){
window._prum = window._prum || [];
push('id', this.options.id);
push('mark', 'firstbyte', date.getTime());
var self = this;
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Pingdom.prototype.loaded = function(){
return !! (window._prum && window._prum.push !== Array.prototype.push);
};
}, {"analytics.js-integration":88,"global-queue":158,"load-date":159}],
67: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_paq');
var each = require('each');
var is = require('is');
/**
* Expose `Piwik` integration.
*/
var Piwik = module.exports = integration('Piwik')
.global('_paq')
.option('url', null)
.option('siteId', '')
.option('customVariableLimit', 5)
.mapping('goals')
.tag('<script src="{{ url }}/piwik.js">');
/**
* Initialize.
*
* http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking
*/
Piwik.prototype.initialize = function(){
window._paq = window._paq || [];
push('setSiteId', this.options.siteId);
push('setTrackerUrl', this.options.url + '/piwik.php');
push('enableLinkTracking');
this.load(this.ready);
};
/**
* Check if Piwik is loaded
*/
Piwik.prototype.loaded = function(){
return !! (window._paq && window._paq.push != [].push);
};
/**
* Page
*
* @param {Page} page
*/
Piwik.prototype.page = function(page){
push('trackPageView');
};
/**
* Track.
*
* @param {Track} track
*/
Piwik.prototype.track = function(track){
var goals = this.goals(track.event());
var revenue = track.revenue();
var category = track.category() || 'All';
var action = track.event();
var name = track.proxy('properties.name') || track.proxy('properties.label');
var value = track.value() || track.revenue();
var options = track.options('Piwik');
var customVariables = options.customVars || options.cvar;
if (!is.object(customVariables)) {
customVariables = {};
}
for (var i = 1; i <= this.options.customVariableLimit; i += 1){
if (customVariables[i]) {
push('setCustomVariable', i.toString(), customVariables[i][0], customVariables[i][1], 'page');
}
}
each(goals, function(goal){
push('trackGoal', goal, revenue);
});
push('trackEvent', category, action, name, value);
};
}, {"analytics.js-integration":88,"global-queue":158,"each":4,"is":91}],
68: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var convertDates = require('convert-dates');
var push = require('global-queue')('_preactq');
var alias = require('alias');
/**
* Expose `Preact` integration.
*/
var Preact = module.exports = integration('Preact')
.assumesPageview()
.global('_preactq')
.global('_lnq')
.option('projectCode', '')
.tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/preact-4.1.min.js">');
/**
* Initialize.
*
* http://www.preact.io/api/javascript
*
* @param {Object} page
*/
Preact.prototype.initialize = function(page){
window._preactq = window._preactq || [];
window._lnq = window._lnq || [];
push('_setCode', this.options.projectCode);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Preact.prototype.loaded = function(){
return !! (window._preactq && window._preactq.push !== Array.prototype.push);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Preact.prototype.identify = function(identify){
if (!identify.userId()) return;
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
push('_setPersonData', {
name: identify.name(),
email: identify.email(),
uid: identify.userId(),
properties: traits
});
};
/**
* Group.
*
* @param {String} id
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Preact.prototype.group = function(group){
if (!group.groupId()) return;
push('_setAccount', group.traits());
};
/**
* Track.
*
* @param {Track} track
*/
Preact.prototype.track = function(track){
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var special = { name: event };
if (revenue) {
special.revenue = revenue * 100;
delete props.revenue;
}
if (props.note) {
special.note = props.note;
delete props.note;
}
push('_logEvent', special, props);
};
/**
* Convert a `date` to a format Preact supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate(date){
return Math.floor(date / 1000);
}
}, {"analytics.js-integration":88,"convert-dates":163,"global-queue":158,"alias":162}],
69: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_kiq');
var Facade = require('facade');
var Identify = Facade.Identify;
var bind = require('bind');
var when = require('when');
/**
* Expose `Qualaroo` integration.
*/
var Qualaroo = module.exports = integration('Qualaroo')
.assumesPageview()
.global('_kiq')
.option('customerId', '')
.option('siteToken', '')
.option('track', false)
.tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Qualaroo.prototype.initialize = function(page){
window._kiq = window._kiq || [];
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load(function(){
when(loaded, ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Qualaroo.prototype.loaded = function(){
return !! (window._kiq && window._kiq.push !== Array.prototype.push);
};
/**
* Identify.
*
* http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers
* http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties
*
* @param {Identify} identify
*/
Qualaroo.prototype.identify = function(identify){
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
if (email) id = email;
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Qualaroo.prototype.track = function(track){
if (!this.options.track) return;
var event = track.event();
var traits = {};
traits['Triggered: ' + event] = true;
this.identify(new Identify({ traits: traits }));
};
}, {"analytics.js-integration":88,"global-queue":158,"facade":132,"bind":101,"when":131}],
70: [function(require, module, exports) {
/**
* Module dependencies.
*/
var push = require('global-queue')('_qevents', { wrap: false });
var integration = require('analytics.js-integration');
var useHttps = require('use-https');
var is = require('is');
var reduce = require('reduce');
/**
* Expose `Quantcast` integration.
*/
var Quantcast = module.exports = integration('Quantcast')
.assumesPageview()
.global('_qevents')
.global('__qc')
.option('pCode', null)
.option('advertise', false)
.tag('http', '<script src="http://edge.quantserve.com/quant.js">')
.tag('https', '<script src="https://secure.quantserve.com/quant.js">');
/**
* Initialize.
*
* https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {Page} page
*/
Quantcast.prototype.initialize = function(page){
window._qevents = window._qevents || [];
var opts = this.options;
var settings = { qacct: opts.pCode };
var user = this.analytics.user();
if (user.id()) settings.uid = user.id();
if (page) {
settings.labels = this._labels('page', page.category(), page.name());
}
push(settings);
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Quantcast.prototype.loaded = function(){
return !! window.__qc;
};
/**
* Page.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Page} page
*/
Quantcast.prototype.page = function(page){
var category = page.category();
var name = page.name();
var customLabels = page.proxy('properties.label')
var labels = this._labels('page', category, name, customLabels);
var settings = {
event: 'refresh',
labels: labels,
qacct: this.options.pCode,
};
var user = this.analytics.user();
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Identify.
*
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {String} id (optional)
*/
Quantcast.prototype.identify = function(identify){
// edit the initial quantcast settings
// TODO: could be done in a cleaner way
var id = identify.userId();
if (id) {
window._qevents[0] = window._qevents[0] || {};
window._qevents[0].uid = id;
}
};
/**
* Track.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Track} track
*/
Quantcast.prototype.track = function(track){
var name = track.event();
var revenue = track.revenue();
var orderId = track.orderId();
var customLabels = track.proxy('properties.label');
var labels = this._labels('event', name, customLabels);
var settings = {
event: 'click',
labels: labels,
qacct: this.options.pCode
};
var user = this.analytics.user();
if (null != revenue) settings.revenue = (revenue+''); // convert to string
if (orderId) settings.orderid = orderId;
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
Quantcast.prototype.completedOrder = function(track){
var name = track.event();
var revenue = track.total();
var customLabels = track.proxy('properties.label')
var labels = this._labels('event', name, customLabels);
var category = track.category();
var repeat = track.proxy('properties.repeat');
if (this.options.advertise && category) {
labels += ',' + this._labels('pcat', category);
}
if ('boolean' == typeof repeat) {
labels += ',_fp.customer.' + (repeat ? 'repeat' : 'new');
}
var settings = {
event: 'refresh', // the example Quantcast sent has completed order send refresh not click
labels: labels,
revenue: (revenue+''), // convert to string
orderid: track.orderId(),
qacct: this.options.pCode
};
push(settings);
};
/**
* Generate quantcast labels.
*
* Example:
*
* options.advertise = false;
* labels('event', 'my event');
* // => "event.my event"
*
* options.advertise = true;
* labels('event', 'my event');
* // => "_fp.event.my event"
*
* @param {String} type
* @param {String} ...
* @return {String}
* @api private
*/
Quantcast.prototype._labels = function(type){
var args = Array.prototype.slice.call(arguments, 1);
var advertise = this.options.advertise;
if (advertise && 'page' == type) type = 'event';
if (advertise) type = '_fp.' + type;
var separator = advertise ? ' ' : '.';
var ret = reduce(args, function(ret, arg){
if (arg != null) {
ret.push(String(arg).replace(/, /g, ','));
}
return ret;
}, []).join(separator);
return [type, ret].join('.');
};
}, {"global-queue":158,"analytics.js-integration":88,"use-https":90,"is":91,"reduce":178}],
178: [function(require, module, exports) {
/**
* Reduce `arr` with `fn`.
*
* @param {Array} arr
* @param {Function} fn
* @param {Mixed} initial
*
* TODO: combatible error handling?
*/
module.exports = function(arr, fn, initial){
var idx = 0;
var len = arr.length;
var curr = arguments.length == 3
? initial
: arr[idx++];
while (idx < len) {
curr = fn.call(null, curr, arr[idx], ++idx, arr);
}
return curr;
};
}, {}],
71: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var extend = require('extend');
var is = require('is');
/**
* Expose `Rollbar` integration.
*/
var RollbarIntegration = module.exports = integration('Rollbar')
.global('Rollbar')
.option('identify', true)
.option('accessToken', '')
.option('environment', 'unknown')
.option('captureUncaught', true);
/**
* Initialize.
*
* @param {Object} page
*/
RollbarIntegration.prototype.initialize = function(page){
var _rollbarConfig = this.config = {
accessToken: this.options.accessToken,
captureUncaught: this.options.captureUncaught,
payload: {
environment: this.options.environment
}
};
// jscs:disable
(function(a,b){function c(b){this.shimId=++h,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function d(b,c,d){a._rollbarWrappedError&&(d[4]||(d[4]=a._rollbarWrappedError),d[5]||(d[5]=a._rollbarWrappedError._rollbarContext),a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function e(b){var d=c;return g(function(){if(this.notifier)return this.notifier[b].apply(this.notifier,arguments);var c=this,e="scope"===b;e&&(c=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:c,method:b,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?c:void 0})}function f(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b&&b._wrapped?b._wrapped:b,c)}}}function g(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var h=0;c.init=function(a,b){var e=b.globalAlias||"Rollbar";if("object"==typeof a[e])return a[e];a._rollbarShimQueue=[],a._rollbarWrappedError=null,b=b||{};var h=new c;return g(function(){if(h.configure(b),b.captureUncaught){var c=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);d(h,c,a)};var g,i,j="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(g=0;g<j.length;++g)i=j[g],a[i]&&a[i].prototype&&f(h,a[i].prototype)}return a[e]=h,h},h.logger)()},c.prototype.loadFull=function(a,b,c,d,e){var f=g(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=g(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}"function"==typeof e&&e(b)},this.logger);g(function(){c?f():a.addEventListener?a.addEventListener("load",f,!1):a.attachEvent("onload",f)},this.logger)()},c.prototype.wrap=function(b,c){try{var d;if(d="function"==typeof c?c:function(){return c||{}},"function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw c._rollbarContext=d(),c._rollbarContext._wrappedSource=b.toString(),a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var e in b)b.hasOwnProperty(e)&&(b._wrapped[e]=b[e])}return b._wrapped}catch(f){return b}};for(var i="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),j=0;j<i.length;++j)c.prototype[i[j]]=e(i[j]);var k="//d37gvrvc0wt4s1.cloudfront.net/js/v1.1/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||k;var l=c.init(a,_rollbarConfig);})(window,document);
// jscs:enable
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
RollbarIntegration.prototype.loaded = function(){
return is.object(window.Rollbar) && null == window.Rollbar.shimId;
};
/**
* Load.
*
* @param {Function} callback
*/
RollbarIntegration.prototype.load = function(callback){
window.Rollbar.loadFull(window, document, true, this.config, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
RollbarIntegration.prototype.identify = function(identify){
// do stuff with `id` or `traits`
if (!this.options.identify) return;
// Don't allow identify without a user id
var uid = identify.userId();
if (uid === null || uid === undefined) return;
var rollbar = window.Rollbar;
var person = { id: uid };
extend(person, identify.traits());
rollbar.configure({ payload: { person: person }});
};
}, {"analytics.js-integration":88,"extend":130,"is":91}],
72: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
/**
* Expose `SaaSquatch` integration.
*/
var SaaSquatch = module.exports = integration('SaaSquatch')
.option('tenantAlias', '')
.option('referralImage', '')
.global('_sqh')
.tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');
/**
* Initialize.
*
* @param {Page} page
*/
SaaSquatch.prototype.initialize = function(page){
window._sqh = window._sqh || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
SaaSquatch.prototype.loaded = function(){
return window._sqh && window._sqh.push != [].push;
};
/**
* Identify.
*
* @param {Facade} identify
*/
SaaSquatch.prototype.identify = function(identify){
var sqh = window._sqh;
var accountId = identify.proxy('traits.accountId');
var paymentProviderId = identify.proxy('traits.paymentProviderId');
var accountStatus = identify.proxy('traits.accountStatus');
var referralCode = identify.proxy('traits.referralCode');
var image = identify.proxy('traits.referralImage') || this.options.referralImage;
var opts = identify.options(this.name);
var id = identify.userId();
var email = identify.email();
if (!(id || email)) return;
if (this.called) return;
var init = {
tenant_alias: this.options.tenantAlias,
first_name: identify.firstName(),
last_name: identify.lastName(),
user_image: identify.avatar(),
email: email,
user_id: id,
};
if (accountId) init.account_id = accountId;
if (paymentProviderId) init.payment_provider_id = paymentProviderId;
if (init.payment_provider_id == "null") init.payment_provider_id = null;
if (accountStatus) init.account_status = accountStatus;
if (referralCode) init.referral_code = referralCode;
if (opts.checksum) init.checksum = opts.checksum;
if (image) init.fb_share_image = image;
sqh.push(['init', init]);
this.called = true;
this.load();
};
/**
* Group.
*
* @param {Group} group
*/
SaaSquatch.prototype.group = function(group){
var sqh = window._sqh;
var props = group.properties();
var id = group.groupId();
var image = group.proxy('traits.referralImage') || this.options.referralImage;
var opts = group.options(this.name);
// tenant_alias is required.
if (this.called) return;
var init = {
tenant_alias: this.options.tenantAlias,
account_id: id
};
if (opts.checksum) init.checksum = opts.checksum;
if (image) init.fb_share_image = image;
sqh.push(['init', init]);
this.called = true;
this.load();
};
}, {"analytics.js-integration":88}],
73: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var when = require('when');
/**
* Expose `SatisMeter` integration.
*/
var SatisMeter = module.exports = integration('SatisMeter')
.global('satismeter')
.option('token', '')
.tag('<script src="https://app.satismeter.com/satismeter.js">');
/**
* Initialize.
*
* @param {Object} page
*/
SatisMeter.prototype.initialize = function(page){
var self = this;
this.load(function(){
when(function(){ return self.loaded(); }, self.ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
SatisMeter.prototype.loaded = function(){
return !!window.satismeter;
};
/**
* Identify.
*
* @param {Identify} identify
*/
SatisMeter.prototype.identify = function(identify){
var traits = identify.traits();
traits.token = this.options.token;
traits.user = {
id: identify.userId()
};
if (identify.name()) {
traits.user.name = identify.name();
}
if (identify.email()) {
traits.user.email = identify.email();
}
if (identify.created()) {
traits.user.signUpDate = identify.created().toISOString();
}
// Remove traits that are already passed in user object
delete traits.id;
delete traits.email;
delete traits.name;
delete traits.created;
window.satismeter(traits);
};
}, {"analytics.js-integration":88,"when":131}],
74: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var localstorage = require('store');
var protocol = require('protocol');
var utm = require('utm-params');
var ads = require('ad-params');
var send = require('send-json');
var cookie = require('cookie');
var clone = require('clone');
var uuid = require('uuid');
var top = require('top-domain');
var extend = require('extend');
var json = require('segmentio/[email protected]');
/**
* Cookie options
*/
var options = {
maxage: 31536000000, // 1y
secure: false,
path: '/'
};
/**
* Expose `Segment` integration.
*/
var Segment = exports = module.exports = integration('Segment.io')
.option('apiKey', '');
/**
* Get the store.
*
* @return {Function}
*/
exports.storage = function(){
return 'file:' == protocol()
|| 'chrome-extension:' == protocol()
? localstorage
: cookie;
};
/**
* Expose global for testing.
*/
exports.global = window;
/**
* Initialize.
*
* https://github.com/segmentio/segmentio/blob/master/modules/segmentjs/segment.js/v1/segment.js
*
* @param {Object} page
*/
Segment.prototype.initialize = function(page){
var self = this;
this.ready();
this.analytics.on('invoke', function(msg){
var action = msg.action();
var listener = 'on' + msg.action();
self.debug('%s %o', action, msg);
if (self[listener]) self[listener](msg);
self.ready();
});
};
/**
* Loaded.
*
* @return {Boolean}
*/
Segment.prototype.loaded = function(){
return true;
};
/**
* Page.
*
* @param {Page} page
*/
Segment.prototype.onpage = function(page){
this.send('/p', page.json());
};
/**
* Identify.
*
* @param {Identify} identify
*/
Segment.prototype.onidentify = function(identify){
this.send('/i', identify.json());
};
/**
* Group.
*
* @param {Group} group
*/
Segment.prototype.ongroup = function(group){
this.send('/g', group.json());
};
/**
* Track.
*
* @param {Track} track
*/
Segment.prototype.ontrack = function(track){
var json = track.json();
delete json.traits; // TODO: figure out why we need traits.
this.send('/t', json);
};
/**
* Alias.
*
* @param {Alias} alias
*/
Segment.prototype.onalias = function(alias){
var json = alias.json();
var user = this.analytics.user();
json.previousId = json.previousId || json.from || user.id() || user.anonymousId();
json.userId = json.userId || json.to;
delete json.from;
delete json.to;
this.send('/a', json);
};
/**
* Normalize the given `msg`.
*
* @param {Object} msg
* @api private
*/
Segment.prototype.normalize = function(msg){
this.debug('normalize %o', msg);
var user = this.analytics.user();
var global = exports.global;
var query = global.location.search;
var ctx = msg.context = msg.context || msg.options || {};
delete msg.options;
msg.writeKey = this.options.apiKey;
ctx.userAgent = navigator.userAgent;
if (!ctx.library) ctx.library = { name: 'analytics.js', version: this.analytics.VERSION };
if (query) ctx.campaign = utm(query);
this.referrerId(query, ctx);
msg.userId = msg.userId || user.id();
msg.anonymousId = user.anonymousId();
msg.messageId = uuid();
msg.sentAt = new Date();
this.debug('normalized %o', msg);
return msg;
};
/**
* Send `obj` to `path`.
*
* @param {String} path
* @param {Object} obj
* @param {Function} fn
* @api private
*/
Segment.prototype.send = function(path, msg, fn){
var url = scheme() + '//api.segment.io/v1' + path;
var headers = { 'Content-Type': 'text/plain' };
var fn = fn || noop;
var self = this;
// msg
msg = this.normalize(msg);
// send
send(url, msg, headers, function(err, res){
self.debug('sent %O, received %O', msg, arguments);
if (err) return fn(err);
res.url = url;
fn(null, res);
});
};
/**
* Gets/sets cookies on the appropriate domain.
*
* @param {String} name
* @param {Mixed} val
*/
Segment.prototype.cookie = function(name, val){
var store = Segment.storage();
if (arguments.length === 1) return store(name);
var global = exports.global;
var href = global.location.href;
var domain = '.' + top(href);
if ('.' == domain) domain = '';
this.debug('store domain %s -> %s', href, domain);
var opts = clone(options);
opts.domain = domain;
this.debug('store %s, %s, %o', name, val, opts);
store(name, val, opts);
if (store(name)) return;
delete opts.domain;
this.debug('fallback store %s, %s, %o', name, val, opts);
store(name, val, opts);
};
/**
* Add referrerId to context.
*
* TODO: remove.
*
* @param {Object} query
* @param {Object} ctx
* @api private
*/
Segment.prototype.referrerId = function(query, ctx){
var stored = this.cookie('s:context.referrer');
var ad;
if (stored) stored = json.parse(stored);
if (query) ad = ads(query);
ad = ad || stored;
if (!ad) return;
ctx.referrer = extend(ctx.referrer || {}, ad);
this.cookie('s:context.referrer', json.stringify(ad));
}
/**
* Get the scheme.
*
* The function returns `http:`
* if the protocol is `http:` and
* `https:` for other protocols.
*
* @return {String}
*/
function scheme(){
return 'http:' == protocol()
? 'http:'
: 'https:';
}
/**
* Noop
*/
function noop(){}
}, {"analytics.js-integration":88,"store":179,"protocol":180,"utm-params":123,"ad-params":181,"send-json":182,"cookie":183,"clone":95,"uuid":184,"top-domain":124,"extend":130,"segmentio/[email protected]":164}],
179: [function(require, module, exports) {
/**
* dependencies.
*/
var unserialize = require('unserialize');
var each = require('each');
var storage;
/**
* Safari throws when a user
* blocks access to cookies / localstorage.
*/
try {
storage = window.localStorage;
} catch (e) {
storage = null;
}
/**
* Expose `store`
*/
module.exports = store;
/**
* Store the given `key`, `val`.
*
* @param {String|Object} key
* @param {Mixed} value
* @return {Mixed}
* @api public
*/
function store(key, value){
var length = arguments.length;
if (0 == length) return all();
if (2 <= length) return set(key, value);
if (1 != length) return;
if (null == key) return storage.clear();
if ('string' == typeof key) return get(key);
if ('object' == typeof key) return each(key, set);
}
/**
* supported flag.
*/
store.supported = !! storage;
/**
* Set `key` to `val`.
*
* @param {String} key
* @param {Mixed} val
*/
function set(key, val){
return null == val
? storage.removeItem(key)
: storage.setItem(key, JSON.stringify(val));
}
/**
* Get `key`.
*
* @param {String} key
* @return {Mixed}
*/
function get(key){
return unserialize(storage.getItem(key));
}
/**
* Get all.
*
* @return {Object}
*/
function all(){
var len = storage.length;
var ret = {};
var key;
while (0 <= --len) {
key = storage.key(len);
ret[key] = get(key);
}
return ret;
}
}, {"unserialize":185,"each":112}],
185: [function(require, module, exports) {
/**
* Unserialize the given "stringified" javascript.
*
* @param {String} val
* @return {Mixed}
*/
module.exports = function(val){
try {
return JSON.parse(val);
} catch (e) {
return val || undefined;
}
};
}, {}],
180: [function(require, module, exports) {
/**
* Convenience alias
*/
var define = Object.defineProperty;
/**
* The base protocol
*/
var initialProtocol = window.location.protocol;
/**
* Fallback mocked protocol in case Object.defineProperty doesn't exist.
*/
var mockedProtocol;
module.exports = function (protocol) {
if (arguments.length === 0) return get();
else return set(protocol);
};
/**
* Sets the protocol to be http:
*/
module.exports.http = function () {
set('http:');
};
/**
* Sets the protocol to be https:
*/
module.exports.https = function () {
set('https:');
};
/**
* Reset to the initial protocol.
*/
module.exports.reset = function () {
set(initialProtocol);
};
/**
* Gets the current protocol, using the fallback and then the native protocol.
*
* @return {String} protocol
*/
function get () {
return mockedProtocol || window.location.protocol;
}
/**
* Sets the protocol
*
* @param {String} protocol
*/
function set (protocol) {
try {
define(window.location, 'protocol', {
get: function () { return protocol; }
});
} catch (err) {
mockedProtocol = protocol;
}
}
}, {}],
181: [function(require, module, exports) {
/**
* Module dependencies.
*/
var parse = require('querystring').parse;
/**
* Expose `ads`
*/
module.exports = ads;
/**
* All the ad query params we look for.
*/
var QUERYIDS = {
'btid' : 'dataxu',
'urid' : 'millennial-media'
};
/**
* Get all ads info from the given `querystring`
*
* @param {String} query
* @return {Object}
* @api private
*/
function ads(query){
var params = parse(query);
for (var key in params) {
for (var id in QUERYIDS) {
if (key === id) {
return {
id : params[key],
type : QUERYIDS[id]
};
}
}
}
}
}, {"querystring":125}],
182: [function(require, module, exports) {
/**
* Module dependencies.
*/
var encode = require('base64-encode');
var cors = require('has-cors');
var jsonp = require('jsonp');
var JSON = require('json');
/**
* Expose `send`
*/
exports = module.exports = cors
? json
: base64;
/**
* Expose `callback`
*/
exports.callback = 'callback';
/**
* Expose `prefix`
*/
exports.prefix = 'data';
/**
* Expose `json`.
*/
exports.json = json;
/**
* Expose `base64`.
*/
exports.base64 = base64;
/**
* Expose `type`
*/
exports.type = cors
? 'xhr'
: 'jsonp';
/**
* Send the given `obj` to `url` with `fn(err, req)`.
*
* @param {String} url
* @param {Object} obj
* @param {Object} headers
* @param {Function} fn
* @api private
*/
function json(url, obj, headers, fn){
if (3 == arguments.length) fn = headers, headers = {};
var req = new XMLHttpRequest;
req.onerror = fn;
req.onreadystatechange = done;
req.open('POST', url, true);
for (var k in headers) req.setRequestHeader(k, headers[k]);
req.send(JSON.stringify(obj));
function done(){
if (4 == req.readyState) return fn(null, req);
}
}
/**
* Send the given `obj` to `url` with `fn(err, req)`.
*
* @param {String} url
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function base64(url, obj, _, fn){
if (3 == arguments.length) fn = _;
var prefix = exports.prefix;
obj = encode(JSON.stringify(obj));
obj = encodeURIComponent(obj);
url += '?' + prefix + '=' + obj;
jsonp(url, { param: exports.callback }, function(err, obj){
if (err) return fn(err);
fn(null, {
url: url,
body: obj
});
});
}
}, {"base64-encode":186,"has-cors":187,"jsonp":188,"json":164}],
186: [function(require, module, exports) {
var utf8Encode = require('utf8-encode');
var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
module.exports = encode;
function encode(input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = utf8Encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
return output;
}
}, {"utf8-encode":189}],
189: [function(require, module, exports) {
module.exports = encode;
function encode(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
}, {}],
187: [function(require, module, exports) {
/**
* Module exports.
*
* Logic borrowed from Modernizr:
*
* - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
*/
try {
module.exports = typeof XMLHttpRequest !== 'undefined' &&
'withCredentials' in new XMLHttpRequest();
} catch (err) {
// if XMLHttp support is disabled in IE then it will throw
// when trying to create
module.exports = false;
}
}, {}],
188: [function(require, module, exports) {
/**
* Module dependencies
*/
var debug = require('debug')('jsonp');
/**
* Module exports.
*/
module.exports = jsonp;
/**
* Callback index.
*/
var count = 0;
/**
* Noop function.
*/
function noop(){}
/**
* JSONP handler
*
* Options:
* - param {String} qs parameter (`callback`)
* - timeout {Number} how long after a timeout error is emitted (`60000`)
*
* @param {String} url
* @param {Object|Function} optional options / callback
* @param {Function} optional callback
*/
function jsonp(url, opts, fn){
if ('function' == typeof opts) {
fn = opts;
opts = {};
}
if (!opts) opts = {};
var prefix = opts.prefix || '__jp';
var param = opts.param || 'callback';
var timeout = null != opts.timeout ? opts.timeout : 60000;
var enc = encodeURIComponent;
var target = document.getElementsByTagName('script')[0] || document.head;
var script;
var timer;
// generate a unique id for this request
var id = prefix + (count++);
if (timeout) {
timer = setTimeout(function(){
cleanup();
if (fn) fn(new Error('Timeout'));
}, timeout);
}
function cleanup(){
script.parentNode.removeChild(script);
window[id] = noop;
}
window[id] = function(data){
debug('jsonp got', data);
if (timer) clearTimeout(timer);
cleanup();
if (fn) fn(null, data);
};
// add qs component
url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id);
url = url.replace('?&', '?');
debug('jsonp req "%s"', url);
// create script
script = document.createElement('script');
script.src = url;
target.parentNode.insertBefore(script, target);
}
}, {"debug":190}],
190: [function(require, module, exports) {
if ('undefined' == typeof window) {
module.exports = require('./lib/debug');
} else {
module.exports = require('./debug');
}
}, {"./lib/debug":191,"./debug":192}],
191: [function(require, module, exports) {
/**
* Module dependencies.
*/
var tty = require('tty');
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Enabled debuggers.
*/
var names = []
, skips = [];
(process.env.DEBUG || '')
.split(/[\s,]+/)
.forEach(function(name){
name = name.replace('*', '.*?');
if (name[0] === '-') {
skips.push(new RegExp('^' + name.substr(1) + '$'));
} else {
names.push(new RegExp('^' + name + '$'));
}
});
/**
* Colors.
*/
var colors = [6, 2, 3, 4, 5, 1];
/**
* Previous debug() call.
*/
var prev = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Is stdout a TTY? Colored output is disabled when `true`.
*/
var isatty = tty.isatty(2);
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function color() {
return colors[prevColor++ % colors.length];
}
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
function humanize(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
}
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
function disabled(){}
disabled.enabled = false;
var match = skips.some(function(re){
return re.test(name);
});
if (match) return disabled;
match = names.some(function(re){
return re.test(name);
});
if (!match) return disabled;
var c = color();
function colored(fmt) {
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (prev[name] || curr);
prev[name] = curr;
fmt = ' \u001b[9' + c + 'm' + name + ' '
+ '\u001b[3' + c + 'm\u001b[90m'
+ fmt + '\u001b[3' + c + 'm'
+ ' +' + humanize(ms) + '\u001b[0m';
console.error.apply(this, arguments);
}
function plain(fmt) {
fmt = coerce(fmt);
fmt = new Date().toUTCString()
+ ' ' + name + ' ' + fmt;
console.error.apply(this, arguments);
}
colored.enabled = plain.enabled = true;
return isatty || process.env.DEBUG_COLORS
? colored
: plain;
}
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
}, {}],
192: [function(require, module, exports) {
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
try {
localStorage.debug = name;
} catch(e){}
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
// persist
try {
if (window.localStorage) debug.enable(localStorage.debug);
} catch(e){}
}, {}],
183: [function(require, module, exports) {
/**
* Module dependencies.
*/
var debug = require('debug')('cookie');
/**
* Set or get cookie `name` with `value` and `options` object.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @return {Mixed}
* @api public
*/
module.exports = function(name, value, options){
switch (arguments.length) {
case 3:
case 2:
return set(name, value, options);
case 1:
return get(name);
default:
return all();
}
};
/**
* Set cookie `name` to `value`.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @api private
*/
function set(name, value, options) {
options = options || {};
var str = encode(name) + '=' + encode(value);
if (null == value) options.maxage = -1;
if (options.maxage) {
options.expires = new Date(+new Date + options.maxage);
}
if (options.path) str += '; path=' + options.path;
if (options.domain) str += '; domain=' + options.domain;
if (options.expires) str += '; expires=' + options.expires.toUTCString();
if (options.secure) str += '; secure';
document.cookie = str;
}
/**
* Return all cookies.
*
* @return {Object}
* @api private
*/
function all() {
return parse(document.cookie);
}
/**
* Get cookie `name`.
*
* @param {String} name
* @return {String}
* @api private
*/
function get(name) {
return all()[name];
}
/**
* Parse cookie `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parse(str) {
var obj = {};
var pairs = str.split(/ *; */);
var pair;
if ('' == pairs[0]) return obj;
for (var i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
obj[decode(pair[0])] = decode(pair[1]);
}
return obj;
}
/**
* Encode.
*/
function encode(value){
try {
return encodeURIComponent(value);
} catch (e) {
debug('error `encode(%o)` - %o', value, e)
}
}
/**
* Decode.
*/
function decode(value) {
try {
return decodeURIComponent(value);
} catch (e) {
debug('error `decode(%o)` - %o', value, e)
}
}
}, {"debug":190}],
184: [function(require, module, exports) {
/**
* Taken straight from jed's gist: https://gist.github.com/982883
*
* Returns a random v4 UUID of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
* where each x is replaced with a random hexadecimal digit from 0 to f, and
* y is replaced with a random hexadecimal digit from 8 to b.
*/
module.exports = function uuid(a){
return a // if the placeholder was passed, return
? ( // a random number from 0 to 15
a ^ // unless b is 8,
Math.random() // in which case
* 16 // a random number from
>> a/4 // 8 to 11
).toString(16) // in hexadecimal
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11 // -100000000000,
).replace( // replacing
/[018]/g, // zeroes, ones, and eights with
uuid // random hex digits
)
};
}, {}],
75: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var is = require('is');
/**
* Expose `Sentry` integration.
*/
var Sentry = module.exports = integration('Sentry')
.global('Raven')
.option('config', '')
.tag('<script src="//cdn.ravenjs.com/1.1.16/native/raven.min.js">');
/**
* Initialize.
*
* http://raven-js.readthedocs.org/en/latest/config/index.html
* https://github.com/getsentry/raven-js/blob/1.1.16/src/raven.js#L734-L741
*/
Sentry.prototype.initialize = function(){
var dsn = this.options.config;
window.RavenConfig = { dsn: dsn };
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Sentry.prototype.loaded = function(){
return is.object(window.Raven);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Sentry.prototype.identify = function(identify){
window.Raven.setUser(identify.traits());
};
}, {"analytics.js-integration":88,"is":91}],
76: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var is = require('is');
var tick = require('next-tick');
/**
* Expose `SnapEngage` integration.
*/
var SnapEngage = module.exports = integration('SnapEngage')
.assumesPageview()
.global('SnapABug')
.global('SnapEngage')
.option('apiKey', '')
.option('listen', false)
.tag('<script src="//www.snapengage.com/cdn/js/{{ apiKey }}.js">');
/**
* Integration object for root events.
*/
var integration = {
name: 'snapengage',
version: '1.0.0'
};
/**
* Initialize.
*
* http://help.snapengage.com/installation-guide-getting-started-in-a-snap/
*
* @param {Object} page
*/
SnapEngage.prototype.initialize = function(page){
var self = this;
this.load(function(){
if (self.options.listen) self.attachListeners();
tick(self.ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
SnapEngage.prototype.loaded = function(){
return is.object(window.SnapABug) && is.object(window.SnapEngage);
};
/**
* Listen for events.
*/
SnapEngage.prototype.attachListeners = function(){
var self = this;
window.SnapEngage.setCallback('StartChat', function(email, message, type){
self.analytics.track('Live Chat Conversation Started',
{},
{ context: { integration: integration } });
});
window.SnapEngage.setCallback('ChatMessageReceived', function(agent, message){
self.analytics.track('Live Chat Message Received',
{ agentUsername: agent },
{ context: { integration: integration } });
});
window.SnapEngage.setCallback('ChatMessageSent', function(message){
self.analytics.track('Live Chat Message Sent',
{},
{ context: { integration: integration }});
});
window.SnapEngage.setCallback('Close', function(type, status){
self.analytics.track('Live Chat Conversation Ended',
{},
{ context: { integration: integration }});
});
};
/**
* Identify.
*
* @param {Identify} identify
*/
SnapEngage.prototype.identify = function(identify){
var email = identify.email();
if (!email) return;
window.SnapABug.setUserEmail(email);
};
}, {"analytics.js-integration":88,"is":91,"next-tick":103}],
77: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var bind = require('bind');
var when = require('when');
/**
* Expose `Spinnakr` integration.
*/
var Spinnakr = module.exports = integration('Spinnakr')
.assumesPageview()
.global('_spinnakr_site_id')
.global('_spinnakr')
.option('siteId', '')
.tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Spinnakr.prototype.initialize = function(page){
window._spinnakr_site_id = this.options.siteId;
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load(function(){
when(loaded, ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Spinnakr.prototype.loaded = function(){
return !! window._spinnakr;
};
}, {"analytics.js-integration":88,"bind":101,"when":131}],
78: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var slug = require('slug');
var push = require('global-queue')('_tsq');
/**
* Expose `Tapstream` integration.
*/
var Tapstream = module.exports = integration('Tapstream')
.assumesPageview()
.global('_tsq')
.option('accountName', '')
.option('trackAllPages', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Tapstream.prototype.initialize = function(page){
window._tsq = window._tsq || [];
push('setAccountName', this.options.accountName);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Tapstream.prototype.loaded = function(){
return !! (window._tsq && window._tsq.push !== Array.prototype.push);
};
/**
* Page.
*
* @param {Page} page
*/
Tapstream.prototype.page = function(page){
var category = page.category();
var opts = this.options;
var name = page.fullName();
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Track.
*
* @param {Track} track
*/
Tapstream.prototype.track = function(track){
var props = track.properties();
push('fireHit', slug(track.event()), [props.url]); // needs events as slugs
};
}, {"analytics.js-integration":88,"slug":99,"global-queue":158}],
79: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var alias = require('alias');
var clone = require('clone');
/**
* Expose `Trakio` integration.
*/
var Trakio = module.exports = integration('trak.io')
.assumesPageview()
.global('trak')
.option('token', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');
/**
* Options aliases.
*/
var optionsAliases = {
initialPageview: 'auto_track_page_view'
};
/**
* Initialize.
*
* https://docs.trak.io
*
* @param {Object} page
*/
Trakio.prototype.initialize = function(page){
var options = this.options;
window.trak = window.trak || [];
window.trak.io = window.trak.io || {};
window.trak.push = window.trak.push || function(){};
window.trak.io.load = window.trak.io.load || function(e){var r = function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); };
window.trak.io.load(options.token, alias(options, optionsAliases));
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Trakio.prototype.loaded = function(){
return !! (window.trak && window.trak.loaded);
};
/**
* Page.
*
* @param {Page} page
*/
Trakio.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
window.trak.io.page_view(props.path, name || props.title);
if (category) window.trak.io.channel('category');
// named pages
if (name && this.options.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && this.options.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Trait aliases.
*
* http://docs.trak.io/properties.html#special
*/
var traitAliases = {
avatar: 'avatar_url',
firstName: 'first_name',
lastName: 'last_name'
};
/**
* Identify.
*
* @param {Identify} identify
*/
Trakio.prototype.identify = function(identify){
var traits = identify.traits(traitAliases);
var id = identify.userId();
if (id) {
window.trak.io.identify(id, traits);
} else {
window.trak.io.identify(traits);
}
};
/**
* Group.
*
* @param {String} id (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*
* TODO: add group
* TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special
*/
/**
* Track.
*
* @param {Track} track
*/
Trakio.prototype.track = function(track){
var properties = track.properties();
var channel = track.proxy('properties.channel');
if (channel) {
delete properties.channel;
window.trak.io.track(track.event(), channel, properties);
} else {
window.trak.io.track(track.event(), properties);
}
};
/**
* Alias.
*
* @param {Alias} alias
*/
Trakio.prototype.alias = function(alias){
if (!window.trak.io.distinct_id) return;
var from = alias.from();
var to = alias.to();
if (to === window.trak.io.distinct_id()) return;
if (from) {
window.trak.io.alias(from, to);
} else {
window.trak.io.alias(to);
}
};
}, {"analytics.js-integration":88,"alias":162,"clone":95}],
80: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var each = require('each');
/**
* HOP.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `TwitterAds`.
*/
var TwitterAds = module.exports = integration('Twitter Ads')
.option('page', '')
.tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>')
.mapping('events');
/**
* Initialize.
*
* @param {Object} page
*/
TwitterAds.prototype.initialize = function(){
this.ready();
};
/**
* Page.
*
* @param {Page} page
*/
TwitterAds.prototype.page = function(page){
if (this.options.page) {
this.load({ pixelId: this.options.page });
}
};
/**
* Track.
*
* @param {Track} track
*/
TwitterAds.prototype.track = function(track){
var events = this.events(track.event());
var self = this;
each(events, function(pixelId){
self.load({ pixelId: pixelId });
});
};
}, {"analytics.js-integration":88,"each":4}],
81: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var Identify = require('facade').Identify;
var clone = require('clone');
/**
* Expose Userlike integration.
*/
var Userlike = module.exports = integration('Userlike')
.assumesPageview()
.global('userlikeConfig')
.global('userlikeData')
.option('secretKey', '')
.option('listen', false)
.tag('<script src="//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/{{ secretKey }}.js">');
/**
* The context for this integration.
*/
var integration = {
name: 'userlike',
version: '1.0.0'
};
/**
* Initialize.
*
* @param {Object} page
*/
Userlike.prototype.initialize = function(page){
var self = this;
var user = this.analytics.user();
var identify = new Identify({
userId: user.id(),
traits: user.traits()
});
segment_base_info = clone(this.options);
segment_base_info.visitor = {
name: identify.name(),
email: identify.email()
};
if (!window.userlikeData) window.userlikeData = { custom: {} };
window.userlikeData.custom.segmentio = segment_base_info;
this.load(function(){
if (self.options.listen) self.attachListeners();
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Userlike.prototype.loaded = function(){
return !! (window.userlikeConfig && window.userlikeData);
};
/**
* Listen for chat events.
*
* TODO: As of 4/17/2015, Userlike doesn't give access to the message body in events.
* Revisit this/send it when they do.
*
*/
Userlike.prototype.attachListeners = function(){
var self = this;
window.userlikeTrackingEvent = function(eventName, globalCtx, sessionCtx){
if (eventName === 'chat_started') {
self.analytics.track(
'Live Chat Conversation Started',
{ agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name },
{ context: { integration: integration }
});
}
if (eventName === 'message_operator_terminating') {
self.analytics.track(
'Live Chat Message Sent',
{ agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name },
{ context: { integration: integration }
});
}
if (eventName === 'message_client_terminating') {
self.analytics.track(
'Live Chat Message Received',
{ agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name },
{ context: { integration: integration }
});
}
if (eventName === 'chat_quit') {
self.analytics.track(
'Live Chat Conversation Ended',
{ agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name },
{ context: { integration: integration }
});
}
};
};
}, {"analytics.js-integration":88,"facade":132,"clone":95}],
82: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('UserVoice');
var convertDates = require('convert-dates');
var unix = require('to-unix-timestamp');
var alias = require('alias');
var clone = require('clone');
/**
* Expose `UserVoice` integration.
*/
var UserVoice = module.exports = integration('UserVoice')
.assumesPageview()
.global('UserVoice')
.global('showClassicWidget')
.option('apiKey', '')
.option('classic', false)
.option('forumId', null)
.option('showWidget', true)
.option('mode', 'contact')
.option('accentColor', '#448dd6')
.option('screenshotEnabled', true)
.option('smartvote', true)
.option('trigger', null)
.option('triggerPosition', 'bottom-right')
.option('triggerColor', '#ffffff')
.option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)')
// BACKWARDS COMPATIBILITY: classic options
.option('classicMode', 'full')
.option('primaryColor', '#cc6d00')
.option('linkColor', '#007dbf')
.option('defaultMode', 'support')
.option('tabLabel', 'Feedback & Support')
.option('tabColor', '#cc6d00')
.option('tabPosition', 'middle-right')
.option('tabInverted', false)
.option('customTicketFields', {})
.tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
UserVoice.on('construct', function(integration){
if (!integration.options.classic) return;
integration.group = undefined;
integration.identify = integration.identifyClassic;
integration.initialize = integration.initializeClassic;
});
/**
* Initialize.
*
* @param {Object} page
*/
UserVoice.prototype.initialize = function(page){
var options = this.options;
var opts = formatOptions(options);
push('set', opts);
push('autoprompt', {});
if (options.showWidget) {
options.trigger
? push('addTrigger', options.trigger, opts)
: push('addTrigger', opts);
}
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
UserVoice.prototype.loaded = function(){
return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push);
};
/**
* Identify.
*
* @param {Identify} identify
*/
UserVoice.prototype.identify = function(identify){
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
UserVoice.prototype.group = function(group){
var traits = group.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', { account: traits });
};
/**
* Initialize (classic).
*
* @param {Object} options
* @param {Function} ready
*/
UserVoice.prototype.initializeClassic = function(){
var options = this.options;
window.showClassicWidget = showClassicWidget; // part of public api
if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options));
this.load(this.ready);
};
/**
* Identify (classic).
*
* @param {Identify} identify
*/
UserVoice.prototype.identifyClassic = function(identify){
push('setCustomFields', identify.traits());
};
/**
* Format the options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatOptions(options){
return alias(options, {
forumId: 'forum_id',
accentColor: 'accent_color',
smartvote: 'smartvote_enabled',
triggerColor: 'trigger_color',
triggerBackgroundColor: 'trigger_background_color',
triggerPosition: 'trigger_position',
screenshotEnabled: 'screenshot_enabled',
customTicketFields: 'ticket_custom_fields'
});
}
/**
* Format the classic options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatClassicOptions(options){
return alias(options, {
forumId: 'forum_id',
classicMode: 'mode',
primaryColor: 'primary_color',
tabPosition: 'tab_position',
tabColor: 'tab_color',
linkColor: 'link_color',
defaultMode: 'default_mode',
tabLabel: 'tab_label',
tabInverted: 'tab_inverted'
});
}
/**
* Show the classic version of the UserVoice widget. This method is usually part
* of UserVoice classic's public API.
*
* @param {String} type ('showTab' or 'showLightbox')
* @param {Object} options (optional)
*/
function showClassicWidget(type, options){
type = type || 'showLightbox';
push(type, 'classic_widget', options);
}
}, {"analytics.js-integration":88,"global-queue":158,"convert-dates":163,"to-unix-timestamp":193,"alias":162,"clone":95}],
193: [function(require, module, exports) {
/**
* Expose `toUnixTimestamp`.
*/
module.exports = toUnixTimestamp;
/**
* Convert a `date` into a Unix timestamp.
*
* @param {Date}
* @return {Number}
*/
function toUnixTimestamp (date) {
return Math.floor(date.getTime() / 1000);
}
}, {}],
83: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_veroq');
var cookie = require('component/cookie');
var objCase = require('obj-case');
/**
* Expose `Vero` integration.
*/
var Vero = module.exports = integration('Vero')
.global('_veroq')
.option('apiKey', '')
.tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');
/**
* Initialize.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md
*
* @param {Object} page
*/
Vero.prototype.initialize = function(page){
// clear default cookie so vero parses correctly.
// this is for the tests.
// basically, they have window.addEventListener('unload')
// which then saves their "command_store", which is an array.
// so we just want to create that initially so we can reload the tests.
if (!cookie('__veroc4')) cookie('__veroc4', '[]');
push('init', { api_key: this.options.apiKey });
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Vero.prototype.loaded = function(){
return !! (window._veroq && window._veroq.push !== Array.prototype.push);
};
/**
* Page.
*
* https://www.getvero.com/knowledge-base#/questions/71768-Does-Vero-track-pageviews
*
* @param {Page} page
*/
Vero.prototype.page = function(page){
push('trackPageview');
};
/**
* Identify.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification
*
* @param {Identify} identify
*/
Vero.prototype.identify = function(identify){
var traits = identify.traits();
var email = identify.email();
var id = identify.userId();
if (!id || !email) return; // both required
push('user', traits);
};
/**
* Track.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events
*
* @param {Track} track
*/
Vero.prototype.track = function(track){
var regex = /[uU]nsubscribe/;
if (track.event().match(regex)) {
push('unsubscribe', { id: track.properties().id });
} else {
push('track', track.event(), track.properties());
}
};
Vero.prototype.alias = function(alias){
var to = alias.to();
if (alias.from()) {
push('reidentify', to, alias.from());
} else {
push('reidentify', to);
}
};
}, {"analytics.js-integration":88,"global-queue":158,"component/cookie":183,"obj-case":92}],
84: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var tick = require('next-tick');
var each = require('each');
/**
* Expose `VWO` integration.
*/
var VWO = module.exports = integration('Visual Website Optimizer')
.option('replay', true);
/**
* Initialize.
*
* http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php
*/
VWO.prototype.initialize = function(){
if (this.options.replay) this.replay();
this.ready();
};
/**
* Completed Purchase.
*
* https://vwo.com/knowledge/vwo-revenue-tracking-goal
*/
VWO.prototype.completedOrder = function(track){
var total = track.total() || track.revenue() || 0;
enqueue(function(){
_vis_opt_revenue_conversion(total);
});
};
/**
* Replay the experiments the user has seen as traits to all other integrations.
* Wait for the next tick to replay so that the `analytics` object and all of
* the integrations are fully initialized.
*/
VWO.prototype.replay = function(){
var analytics = this.analytics;
tick(function(){
experiments(function(err, traits){
if (traits) analytics.identify(traits);
});
});
};
/**
* Get dictionary of experiment keys and variations.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {Function} fn
* @return {Object}
*/
function experiments(fn){
enqueue(function(){
var data = {};
var ids = window._vwo_exp_ids;
if (!ids) return fn();
each(ids, function(id){
var name = variation(id);
if (name) data['Experiment: ' + id] = name;
});
fn(null, data);
});
}
/**
* Add a `fn` to the VWO queue, creating one if it doesn't exist.
*
* @param {Function} fn
*/
function enqueue(fn){
window._vis_opt_queue = window._vis_opt_queue || [];
window._vis_opt_queue.push(fn);
}
/**
* Get the chosen variation's name from an experiment `id`.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {String} id
* @return {String}
*/
function variation(id){
var experiments = window._vwo_exp;
if (!experiments) return null;
var experiment = experiments[id];
var variationId = experiment.combination_chosen;
return variationId ? experiment.comb_n[variationId] : null;
}
}, {"analytics.js-integration":88,"next-tick":103,"each":4}],
85: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var useHttps = require('use-https');
/**
* Expose `WebEngage` integration.
*/
var WebEngage = module.exports = integration('WebEngage')
.assumesPageview()
.global('_weq')
.global('webengage')
.option('widgetVersion', '4.0')
.option('licenseCode', '')
.tag('http', '<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">')
.tag('https', '<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');
/**
* Initialize.
*
* @param {Object} page
*/
WebEngage.prototype.initialize = function(page){
var _weq = window._weq = window._weq || {};
_weq['webengage.licenseCode'] = this.options.licenseCode;
_weq['webengage.widgetVersion'] = this.options.widgetVersion;
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
WebEngage.prototype.loaded = function(){
return !! window.webengage;
};
}, {"analytics.js-integration":88,"use-https":90}],
86: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var snake = require('to-snake-case');
var isEmail = require('is-email');
var extend = require('extend');
var each = require('each');
var type = require('type');
/**
* Expose `Woopra` integration.
*/
var Woopra = module.exports = integration('Woopra')
.global('woopra')
.option('domain', '')
.option('cookieName', 'wooTracker')
.option('cookieDomain', null)
.option('cookiePath', '/')
.option('ping', true)
.option('pingInterval', 12000)
.option('idleTimeout', 300000)
.option('downloadTracking', true)
.option('outgoingTracking', true)
.option('outgoingIgnoreSubdomain', true)
.option('downloadPause', 200)
.option('outgoingPause', 400)
.option('ignoreQueryUrl', true)
.option('hideCampaign', false)
.tag('<script src="//static.woopra.com/js/w.js">');
/**
* Initialize.
*
* http://www.woopra.com/docs/setup/javascript-tracking/
*
* @param {Object} page
*/
Woopra.prototype.initialize = function(page){
(function(){var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function(){var i, self = this; self._e = []; for (i = 0; i < f.length; i++){(function(f){self[f] = function(){self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++){ w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra');
this.load(this.ready);
each(this.options, function(key, value){
key = snake(key);
if (null == value) return;
if ('' === value) return;
window.woopra.config(key, value);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Woopra.prototype.loaded = function(){
return !! (window.woopra && window.woopra.loaded);
};
/**
* Page.
*
* @param {String} category (optional)
*/
Woopra.prototype.page = function(page){
var props = page.properties();
var name = page.fullName();
if (name) props.title = name;
window.woopra.track('pv', props);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Woopra.prototype.identify = function(identify){
var traits = identify.traits();
if (identify.name()) traits.name = identify.name();
window.woopra.identify(traits).push(); // `push` sends it off async
};
/**
* Track.
*
* @param {Track} track
*/
Woopra.prototype.track = function(track){
window.woopra.track(track.event(), track.properties());
};
}, {"analytics.js-integration":88,"to-snake-case":89,"is-email":154,"extend":130,"each":4,"type":113}],
87: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var tick = require('next-tick');
var bind = require('bind');
var when = require('when');
/**
* Expose `Yandex` integration.
*/
var Yandex = module.exports = integration('Yandex Metrica')
.assumesPageview()
.global('yandex_metrika_callbacks')
.global('Ya')
.option('counterId', null)
.option('clickmap', false)
.option('webvisor', false)
.tag('<script src="//mc.yandex.ru/metrika/watch.js">');
/**
* Initialize.
*
* http://api.yandex.com/metrika/
* https://metrica.yandex.com/22522351?step=2#tab=code
*
* @param {Object} page
*/
Yandex.prototype.initialize = function(page){
var id = this.options.counterId;
var clickmap = this.options.clickmap;
var webvisor = this.options.webvisor;
push(function(){
window['yaCounter' + id] = new window.Ya.Metrika({
id: id,
clickmap: clickmap,
webvisor: webvisor
});
});
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load(function(){
when(loaded, function(){
tick(ready);
});
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Yandex.prototype.loaded = function(){
return !! (window.Ya && window.Ya.Metrika);
};
/**
* Push a new callback on the global Yandex queue.
*
* @param {Function} callback
*/
function push(callback){
window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || [];
window.yandex_metrika_callbacks.push(callback);
}
}, {"analytics.js-integration":88,"next-tick":103,"bind":101,"when":131}],
3: [function(require, module, exports) {
var _analytics = window.analytics;
var after = require('after');
var bind = require('bind');
var callback = require('callback');
var clone = require('clone');
var cookie = require('./cookie');
var debug = require('debug');
var defaults = require('defaults');
var each = require('each');
var Emitter = require('emitter');
var group = require('./group');
var is = require('is');
var isEmail = require('is-email');
var isMeta = require('is-meta');
var newDate = require('new-date');
var on = require('event').bind;
var pageDefaults = require('./pageDefaults');
var pick = require('pick');
var prevent = require('prevent');
var querystring = require('querystring');
var normalize = require('./normalize');
var size = require('object').length;
var keys = require('object').keys;
var memory = require('./memory');
var store = require('./store');
var user = require('./user');
var Facade = require('facade');
var Identify = Facade.Identify;
var Group = Facade.Group;
var Alias = Facade.Alias;
var Track = Facade.Track;
var Page = Facade.Page;
/**
* Expose `Analytics`.
*/
exports = module.exports = Analytics;
/**
* Expose storage.
*/
exports.cookie = cookie;
exports.store = store;
exports.memory = memory;
/**
* Initialize a new `Analytics` instance.
*/
function Analytics () {
this._options({});
this.Integrations = {};
this._integrations = {};
this._readied = false;
this._timeout = 300;
this._user = user; // BACKWARDS COMPATIBILITY
this.log = debug('analytics.js');
bind.all(this);
var self = this;
this.on('initialize', function(settings, options){
if (options.initialPageview) self.page();
self._parseQuery();
});
}
/**
* Event Emitter.
*/
Emitter(Analytics.prototype);
/**
* Use a `plugin`.
*
* @param {Function} plugin
* @return {Analytics}
*/
Analytics.prototype.use = function (plugin) {
plugin(this);
return this;
};
/**
* Define a new `Integration`.
*
* @param {Function} Integration
* @return {Analytics}
*/
Analytics.prototype.addIntegration = function (Integration) {
var name = Integration.prototype.name;
if (!name) throw new TypeError('attempted to add an invalid integration');
this.Integrations[name] = Integration;
return this;
};
/**
* Initialize with the given integration `settings` and `options`. Aliased to
* `init` for convenience.
*
* @param {Object} settings
* @param {Object} options (optional)
* @return {Analytics}
*/
Analytics.prototype.init =
Analytics.prototype.initialize = function (settings, options) {
settings = settings || {};
options = options || {};
this._options(options);
this._readied = false;
// clean unknown integrations from settings
var self = this;
each(settings, function (name) {
var Integration = self.Integrations[name];
if (!Integration) delete settings[name];
});
// add integrations
each(settings, function (name, opts) {
var Integration = self.Integrations[name];
var integration = new Integration(clone(opts));
self.log('initialize %o - %o', name, opts);
self.add(integration);
});
var integrations = this._integrations;
// load user now that options are set
user.load();
group.load();
// make ready callback
var ready = after(size(integrations), function () {
self._readied = true;
self.emit('ready');
});
// initialize integrations, passing ready
each(integrations, function (name, integration) {
if (options.initialPageview && integration.options.initialPageview === false) {
integration.page = after(2, integration.page);
}
integration.analytics = self;
integration.once('ready', ready);
integration.initialize();
});
// backwards compat with angular plugin.
// TODO: remove
this.initialized = true;
this.emit('initialize', settings, options);
return this;
};
/**
* Set the user's `id`.
*
* @param {Mixed} id
*/
Analytics.prototype.setAnonymousId = function(id){
this.user().anonymousId(id);
return this;
};
/**
* Add an integration.
*
* @param {Integration} integration
*/
Analytics.prototype.add = function(integration){
this._integrations[integration.name] = integration;
return this;
};
/**
* Identify a user by optional `id` and `traits`.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.identify = function (id, traits, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = user.id();
// clone traits before we manipulate so we don't do anything uncouth, and take
// from `user` so that we carryover anonymous traits
user.identify(id, traits);
var msg = this.normalize({
options: options,
traits: user.traits(),
userId: user.id(),
});
this._invoke('identify', new Identify(msg));
// emit
this.emit('identify', id, traits, options);
this._callback(fn);
return this;
};
/**
* Return the current user.
*
* @return {Object}
*/
Analytics.prototype.user = function () {
return user;
};
/**
* Identify a group by optional `id` and `traits`. Or, if no arguments are
* supplied, return the current group.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics or Object}
*/
Analytics.prototype.group = function (id, traits, options, fn) {
if (0 === arguments.length) return group;
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = group.id();
// grab from group again to make sure we're taking from the source
group.identify(id, traits);
var msg = this.normalize({
options: options,
traits: group.traits(),
groupId: group.id()
});
this._invoke('group', new Group(msg));
this.emit('group', id, traits, options);
this._callback(fn);
return this;
};
/**
* Track an `event` that a user has triggered with optional `properties`.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.track = function (event, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = null, properties = null;
// figure out if the event is archived.
var plan = this.options.plan || {};
var events = plan.track || {};
// normalize
var msg = this.normalize({
properties: properties,
options: options,
event: event
});
// plan.
if (plan = events[event]) {
this.log('plan %o - %o', event, plan);
if (false == plan.enabled) return this._callback(fn);
defaults(msg.integrations, plan.integrations || {});
}
this._invoke('track', new Track(msg));
this.emit('track', event, properties, options);
this._callback(fn);
return this;
};
/**
* Helper method to track an outbound link that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackClick`.
*
* @param {Element or Array} links
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackClick =
Analytics.prototype.trackLink = function (links, event, properties) {
if (!links) return this;
if (is.element(links)) links = [links]; // always arrays, handles jquery
var self = this;
each(links, function (el) {
if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackLink`.');
on(el, 'click', function (e) {
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
var href = el.getAttribute('href')
|| el.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
|| el.getAttribute('xlink:href');
self.track(ev, props);
if (href && el.target !== '_blank' && !isMeta(e)) {
prevent(e);
self._callback(function () {
window.location.href = href;
});
}
});
});
return this;
};
/**
* Helper method to track an outbound form that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackSubmit`.
*
* @param {Element or Array} forms
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackSubmit =
Analytics.prototype.trackForm = function (forms, event, properties) {
if (!forms) return this;
if (is.element(forms)) forms = [forms]; // always arrays, handles jquery
var self = this;
each(forms, function (el) {
if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackForm`.');
function handler (e) {
prevent(e);
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
self._callback(function () {
el.submit();
});
}
// support the events happening through jQuery or Zepto instead of through
// the normal DOM API, since `el.submit` doesn't bubble up events...
var $ = window.jQuery || window.Zepto;
if ($) {
$(el).submit(handler);
} else {
on(el, 'submit', handler);
}
});
return this;
};
/**
* Trigger a pageview, labeling the current page with an optional `category`,
* `name` and `properties`.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object or String} properties (or path) (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.page = function (category, name, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = properties = null;
if (is.fn(name)) fn = name, options = properties = name = null;
if (is.object(category)) options = name, properties = category, name = category = null;
if (is.object(name)) options = properties, properties = name, name = null;
if (is.string(category) && !is.string(name)) name = category, category = null;
properties = clone(properties) || {};
if (name) properties.name = name;
if (category) properties.category = category;
// Ensure properties has baseline spec properties.
// TODO: Eventually move these entirely to `options.context.page`
var defs = pageDefaults();
defaults(properties, defs);
// Mirror user overrides to `options.context.page` (but exclude custom properties)
// (Any page defaults get applied in `this.normalize` for consistency.)
// Weird, yeah--moving special props to `context.page` will fix this in the long term.
var overrides = pick(keys(defs), properties);
if (!is.empty(overrides)) {
options = options || {};
options.context = options.context || {};
options.context.page = overrides;
}
var msg = this.normalize({
properties: properties,
category: category,
options: options,
name: name
});
this._invoke('page', new Page(msg));
this.emit('page', category, name, properties, options);
this._callback(fn);
return this;
};
/**
* BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call.
*
* @param {String} url (optional)
* @param {Object} options (optional)
* @return {Analytics}
* @api private
*/
Analytics.prototype.pageview = function (url, options) {
var properties = {};
if (url) properties.path = url;
this.page(properties);
return this;
};
/**
* Merge two previously unassociated user identities.
*
* @param {String} to
* @param {String} from (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.alias = function (to, from, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(from)) fn = from, options = null, from = null;
if (is.object(from)) options = from, from = null;
var msg = this.normalize({
options: options,
previousId: from,
userId: to
});
this._invoke('alias', new Alias(msg));
this.emit('alias', to, from, options);
this._callback(fn);
return this;
};
/**
* Register a `fn` to be fired when all the analytics services are ready.
*
* @param {Function} fn
* @return {Analytics}
*/
Analytics.prototype.ready = function (fn) {
if (!is.fn(fn)) return this;
this._readied
? callback.async(fn)
: this.once('ready', fn);
return this;
};
/**
* Set the `timeout` (in milliseconds) used for callbacks.
*
* @param {Number} timeout
*/
Analytics.prototype.timeout = function (timeout) {
this._timeout = timeout;
};
/**
* Enable or disable debug.
*
* @param {String or Boolean} str
*/
Analytics.prototype.debug = function(str){
if (0 == arguments.length || str) {
debug.enable('analytics:' + (str || '*'));
} else {
debug.disable();
}
};
/**
* Apply options.
*
* @param {Object} options
* @return {Analytics}
* @api private
*/
Analytics.prototype._options = function (options) {
options = options || {};
this.options = options;
cookie.options(options.cookie);
store.options(options.localStorage);
user.options(options.user);
group.options(options.group);
return this;
};
/**
* Callback a `fn` after our defined timeout period.
*
* @param {Function} fn
* @return {Analytics}
* @api private
*/
Analytics.prototype._callback = function (fn) {
callback.async(fn, this._timeout);
return this;
};
/**
* Call `method` with `facade` on all enabled integrations.
*
* @param {String} method
* @param {Facade} facade
* @return {Analytics}
* @api private
*/
Analytics.prototype._invoke = function (method, facade) {
var options = facade.options();
this.emit('invoke', facade);
each(this._integrations, function (name, integration) {
if (!facade.enabled(name)) return;
integration.invoke.call(integration, method, facade);
});
return this;
};
/**
* Push `args`.
*
* @param {Array} args
* @api private
*/
Analytics.prototype.push = function(args){
var method = args.shift();
if (!this[method]) return;
this[method].apply(this, args);
};
/**
* Reset group and user traits and id's.
*
* @api public
*/
Analytics.prototype.reset = function(){
this.user().logout();
this.group().logout();
};
/**
* Parse the query string for callable methods.
*
* @return {Analytics}
* @api private
*/
Analytics.prototype._parseQuery = function () {
// Identify and track any `ajs_uid` and `ajs_event` parameters in the URL.
var q = querystring.parse(window.location.search);
if (q.ajs_uid) this.identify(q.ajs_uid);
if (q.ajs_event) this.track(q.ajs_event);
if (q.ajs_aid) user.anonymousId(q.ajs_aid);
return this;
};
/**
* Normalize the given `msg`.
*
* @param {Object} msg
* @return {Object}
*/
Analytics.prototype.normalize = function(msg){
msg = normalize(msg, keys(this._integrations));
if (msg.anonymousId) user.anonymousId(msg.anonymousId);
msg.anonymousId = user.anonymousId();
// Ensure all outgoing requests include page data in their contexts.
msg.context.page = defaults(msg.context.page || {}, pageDefaults());
return msg;
};
/**
* No conflict support.
*/
Analytics.prototype.noConflict = function(){
window.analytics = _analytics;
return this;
};
}, {"after":111,"bind":194,"callback":94,"clone":95,"./cookie":195,"debug":190,"defaults":97,"each":4,"emitter":110,"./group":196,"is":91,"is-email":154,"is-meta":197,"new-date":146,"event":198,"./pageDefaults":199,"pick":200,"prevent":201,"querystring":202,"./normalize":203,"object":170,"./memory":204,"./store":205,"./user":206,"facade":132}],
194: [function(require, module, exports) {
try {
var bind = require('bind');
} catch (e) {
var bind = require('bind-component');
}
var bindAll = require('bind-all');
/**
* Expose `bind`.
*/
module.exports = exports = bind;
/**
* Expose `bindAll`.
*/
exports.all = bindAll;
/**
* Expose `bindMethods`.
*/
exports.methods = bindMethods;
/**
* Bind `methods` on `obj` to always be called with the `obj` as context.
*
* @param {Object} obj
* @param {String} methods...
*/
function bindMethods (obj, methods) {
methods = [].slice.call(arguments, 1);
for (var i = 0, method; method = methods[i]; i++) {
obj[method] = bind(obj, obj[method]);
}
return obj;
}
}, {"bind":101,"bind-all":102}],
195: [function(require, module, exports) {
var debug = require('debug')('analytics.js:cookie');
var bind = require('bind');
var cookie = require('cookie');
var clone = require('clone');
var defaults = require('defaults');
var json = require('json');
var topDomain = require('top-domain');
/**
* Initialize a new `Cookie` with `options`.
*
* @param {Object} options
*/
function Cookie (options) {
this.options(options);
}
/**
* Get or set the cookie options.
*
* @param {Object} options
* @field {Number} maxage (1 year)
* @field {String} domain
* @field {String} path
* @field {Boolean} secure
*/
Cookie.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
var domain = '.' + topDomain(window.location.href);
this._options = defaults(options, {
maxage: 31536000000, // default to a year
path: '/',
domain: domain
});
// http://curl.haxx.se/rfc/cookie_spec.html
// https://publicsuffix.org/list/effective_tld_names.dat
//
// try setting a dummy cookie with the options
// if the cookie isn't set, it probably means
// that the domain is on the public suffix list
// like myapp.herokuapp.com or localhost / ip.
this.set('ajs:test', true);
if (!this.get('ajs:test')) {
debug('fallback to domain=null');
this._options.domain = null;
}
this.remove('ajs:test');
};
/**
* Set a `key` and `value` in our cookie.
*
* @param {String} key
* @param {Object} value
* @return {Boolean} saved
*/
Cookie.prototype.set = function (key, value) {
try {
value = json.stringify(value);
cookie(key, value, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Get a value from our cookie by `key`.
*
* @param {String} key
* @return {Object} value
*/
Cookie.prototype.get = function (key) {
try {
var value = cookie(key);
value = value ? json.parse(value) : null;
return value;
} catch (e) {
return null;
}
};
/**
* Remove a value from our cookie by `key`.
*
* @param {String} key
* @return {Boolean} removed
*/
Cookie.prototype.remove = function (key) {
try {
cookie(key, null, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Expose the cookie singleton.
*/
module.exports = bind.all(new Cookie());
/**
* Expose the `Cookie` constructor.
*/
module.exports.Cookie = Cookie;
}, {"debug":190,"bind":194,"cookie":183,"clone":95,"defaults":97,"json":164,"top-domain":124}],
196: [function(require, module, exports) {
var debug = require('debug')('analytics:group');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
/**
* Group defaults
*/
Group.defaults = {
persist: true,
cookie: {
key: 'ajs_group_id'
},
localStorage: {
key: 'ajs_group_properties'
}
};
/**
* Initialize a new `Group` with `options`.
*
* @param {Object} options
*/
function Group (options) {
this.defaults = Group.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(Group, Entity);
/**
* Expose the group singleton.
*/
module.exports = bind.all(new Group());
/**
* Expose the `Group` constructor.
*/
module.exports.Group = Group;
}, {"debug":190,"./entity":207,"inherit":208,"bind":194}],
207: [function(require, module, exports) {
var debug = require('debug')('analytics:entity');
var traverse = require('isodate-traverse');
var defaults = require('defaults');
var memory = require('./memory');
var cookie = require('./cookie');
var store = require('./store');
var extend = require('extend');
var clone = require('clone');
/**
* Expose `Entity`
*/
module.exports = Entity;
/**
* Initialize new `Entity` with `options`.
*
* @param {Object} options
*/
function Entity(options){
this.options(options);
this.initialize();
}
/**
* Initialize picks the storage.
*
* Checks to see if cookies can be set
* otherwise fallsback to localStorage.
*/
Entity.prototype.initialize = function(){
cookie.set('ajs:cookies', true);
// cookies are enabled.
if (cookie.get('ajs:cookies')) {
cookie.remove('ajs:cookies');
this._storage = cookie;
return;
}
// localStorage is enabled.
if (store.enabled) {
this._storage = store;
return;
}
// fallback to memory storage.
debug('warning using memory store both cookies and localStorage are disabled');
this._storage = memory;
};
/**
* Get the storage.
*/
Entity.prototype.storage = function(){
return this._storage;
};
/**
* Get or set storage `options`.
*
* @param {Object} options
* @property {Object} cookie
* @property {Object} localStorage
* @property {Boolean} persist (default: `true`)
*/
Entity.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options || (options = {});
defaults(options, this.defaults || {});
this._options = options;
};
/**
* Get or set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype.id = function (id) {
switch (arguments.length) {
case 0: return this._getId();
case 1: return this._setId(id);
}
};
/**
* Get the entity's id.
*
* @return {String}
*/
Entity.prototype._getId = function () {
var ret = this._options.persist
? this.storage().get(this._options.cookie.key)
: this._id;
return ret === undefined ? null : ret;
};
/**
* Set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype._setId = function (id) {
if (this._options.persist) {
this.storage().set(this._options.cookie.key, id);
} else {
this._id = id;
}
};
/**
* Get or set the entity's `traits`.
*
* BACKWARDS COMPATIBILITY: aliased to `properties`
*
* @param {Object} traits
*/
Entity.prototype.properties =
Entity.prototype.traits = function (traits) {
switch (arguments.length) {
case 0: return this._getTraits();
case 1: return this._setTraits(traits);
}
};
/**
* Get the entity's traits. Always convert ISO date strings into real dates,
* since they aren't parsed back from local storage.
*
* @return {Object}
*/
Entity.prototype._getTraits = function () {
var ret = this._options.persist
? store.get(this._options.localStorage.key)
: this._traits;
return ret ? traverse(clone(ret)) : {};
};
/**
* Set the entity's `traits`.
*
* @param {Object} traits
*/
Entity.prototype._setTraits = function (traits) {
traits || (traits = {});
if (this._options.persist) {
store.set(this._options.localStorage.key, traits);
} else {
this._traits = traits;
}
};
/**
* Identify the entity with an `id` and `traits`. If we it's the same entity,
* extend the existing `traits` instead of overwriting.
*
* @param {String} id
* @param {Object} traits
*/
Entity.prototype.identify = function (id, traits) {
traits || (traits = {});
var current = this.id();
if (current === null || current === id) traits = extend(this.traits(), traits);
if (id) this.id(id);
this.debug('identify %o, %o', id, traits);
this.traits(traits);
this.save();
};
/**
* Save the entity to local storage and the cookie.
*
* @return {Boolean}
*/
Entity.prototype.save = function () {
if (!this._options.persist) return false;
cookie.set(this._options.cookie.key, this.id());
store.set(this._options.localStorage.key, this.traits());
return true;
};
/**
* Log the entity out, reseting `id` and `traits` to defaults.
*/
Entity.prototype.logout = function () {
this.id(null);
this.traits({});
cookie.remove(this._options.cookie.key);
store.remove(this._options.localStorage.key);
};
/**
* Reset all entity state, logging out and returning options to defaults.
*/
Entity.prototype.reset = function () {
this.logout();
this.options({});
};
/**
* Load saved entity `id` or `traits` from storage.
*/
Entity.prototype.load = function () {
this.id(cookie.get(this._options.cookie.key));
this.traits(store.get(this._options.localStorage.key));
};
}, {"debug":190,"isodate-traverse":142,"defaults":97,"./memory":204,"./cookie":195,"./store":205,"extend":130,"clone":95}],
204: [function(require, module, exports) {
/**
* Module Dependencies.
*/
var clone = require('clone');
var bind = require('bind');
/**
* HOP.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Memory`
*/
module.exports = bind.all(new Memory);
/**
* Initialize `Memory` store
*/
function Memory(){
this.store = {};
}
/**
* Set a `key` and `value`.
*
* @param {String} key
* @param {Mixed} value
* @return {Boolean}
*/
Memory.prototype.set = function(key, value){
this.store[key] = clone(value);
return true;
};
/**
* Get a `key`.
*
* @param {String} key
*/
Memory.prototype.get = function(key){
if (!has.call(this.store, key)) return;
return clone(this.store[key]);
};
/**
* Remove a `key`.
*
* @param {String} key
* @return {Boolean}
*/
Memory.prototype.remove = function(key){
delete this.store[key];
return true;
};
}, {"clone":95,"bind":194}],
205: [function(require, module, exports) {
var bind = require('bind');
var defaults = require('defaults');
var store = require('store.js');
/**
* Initialize a new `Store` with `options`.
*
* @param {Object} options
*/
function Store (options) {
this.options(options);
}
/**
* Set the `options` for the store.
*
* @param {Object} options
* @field {Boolean} enabled (true)
*/
Store.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
defaults(options, { enabled : true });
this.enabled = options.enabled && store.enabled;
this._options = options;
};
/**
* Set a `key` and `value` in local storage.
*
* @param {String} key
* @param {Object} value
*/
Store.prototype.set = function (key, value) {
if (!this.enabled) return false;
return store.set(key, value);
};
/**
* Get a value from local storage by `key`.
*
* @param {String} key
* @return {Object}
*/
Store.prototype.get = function (key) {
if (!this.enabled) return null;
return store.get(key);
};
/**
* Remove a value from local storage by `key`.
*
* @param {String} key
*/
Store.prototype.remove = function (key) {
if (!this.enabled) return false;
return store.remove(key);
};
/**
* Expose the store singleton.
*/
module.exports = bind.all(new Store());
/**
* Expose the `Store` constructor.
*/
module.exports.Store = Store;
}, {"bind":194,"defaults":97,"store.js":209}],
209: [function(require, module, exports) {
var json = require('json')
, store = {}
, win = window
, doc = win.document
, localStorageName = 'localStorage'
, namespace = '__storejs__'
, storage;
store.disabled = false
store.set = function(key, value) {}
store.get = function(key) {}
store.remove = function(key) {}
store.clear = function() {}
store.transact = function(key, defaultVal, transactionFn) {
var val = store.get(key)
if (transactionFn == null) {
transactionFn = defaultVal
defaultVal = null
}
if (typeof val == 'undefined') { val = defaultVal || {} }
transactionFn(val)
store.set(key, val)
}
store.getAll = function() {}
store.serialize = function(value) {
return json.stringify(value)
}
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return json.parse(value) }
catch(e) { return value || undefined }
}
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try { return (localStorageName in win && win[localStorageName]) }
catch(err) { return false }
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName]
store.set = function(key, val) {
if (val === undefined) { return store.remove(key) }
storage.setItem(key, store.serialize(val))
return val
}
store.get = function(key) { return store.deserialize(storage.getItem(key)) }
store.remove = function(key) { storage.removeItem(key) }
store.clear = function() { storage.clear() }
store.getAll = function() {
var ret = {}
for (var i=0; i<storage.length; ++i) {
var key = storage.key(i)
ret[key] = store.get(key)
}
return ret
}
} else if (doc.documentElement.addBehavior) {
var storageOwner,
storageContainer
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storage = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div')
storageOwner = doc.body
}
function withIEStorage(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift(storage)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage)
storage.addBehavior('#default#userData')
storage.load(localStorageName)
var result = storeFunction.apply(store, args)
storageOwner.removeChild(storage)
return result
}
}
// In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
function ieKeyFix(key) {
return key.replace(forbiddenCharsRegex, '___')
}
store.set = withIEStorage(function(storage, key, val) {
key = ieKeyFix(key)
if (val === undefined) { return store.remove(key) }
storage.setAttribute(key, store.serialize(val))
storage.save(localStorageName)
return val
})
store.get = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
return store.deserialize(storage.getAttribute(key))
})
store.remove = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
storage.removeAttribute(key)
storage.save(localStorageName)
})
store.clear = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
storage.load(localStorageName)
for (var i=0, attr; attr=attributes[i]; i++) {
storage.removeAttribute(attr.name)
}
storage.save(localStorageName)
})
store.getAll = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
var ret = {}
for (var i=0, attr; attr=attributes[i]; ++i) {
var key = ieKeyFix(attr.name)
ret[attr.name] = store.deserialize(storage.getAttribute(key))
}
return ret
})
}
try {
store.set(namespace, namespace)
if (store.get(namespace) != namespace) { store.disabled = true }
store.remove(namespace)
} catch(e) {
store.disabled = true
}
store.enabled = !store.disabled
module.exports = store;
}, {"json":164}],
208: [function(require, module, exports) {
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
}, {}],
197: [function(require, module, exports) {
module.exports = function isMeta (e) {
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true;
// Logic that handles checks for the middle mouse button, based
// on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466).
var which = e.which, button = e.button;
if (!which && button !== undefined) {
return (!button & 1) && (!button & 2) && (button & 4);
} else if (which === 2) {
return true;
}
return false;
};
}, {}],
198: [function(require, module, exports) {
/**
* Bind `el` event `type` to `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.bind = function(el, type, fn, capture){
if (el.addEventListener) {
el.addEventListener(type, fn, capture || false);
} else {
el.attachEvent('on' + type, fn);
}
return fn;
};
/**
* Unbind `el` event `type`'s callback `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.unbind = function(el, type, fn, capture){
if (el.removeEventListener) {
el.removeEventListener(type, fn, capture || false);
} else {
el.detachEvent('on' + type, fn);
}
return fn;
};
}, {}],
199: [function(require, module, exports) {
/**
* Module dependencies.
*/
var canonical = require('canonical');
var url = require('url');
/**
* Return a default `options.context.page` object.
*
* https://segment.com/docs/spec/page/#properties
*
* @return {Object}
*/
function pageDefaults() {
return {
path: canonicalPath(),
referrer: document.referrer,
search: location.search,
title: document.title,
url: canonicalUrl(location.search)
};
}
/**
* Return the canonical path for the page.
*
* @return {String}
*/
function canonicalPath () {
var canon = canonical();
if (!canon) return window.location.pathname;
var parsed = url.parse(canon);
return parsed.pathname;
}
/**
* Return the canonical URL for the page concat the given `search`
* and strip the hash.
*
* @param {String} search
* @return {String}
*/
function canonicalUrl (search) {
var canon = canonical();
if (canon) return ~canon.indexOf('?') ? canon : canon + search;
var url = window.location.href;
var i = url.indexOf('#');
return -1 === i ? url : url.slice(0, i);
}
/**
* Exports.
*/
module.exports = pageDefaults;
}, {"canonical":171,"url":173}],
200: [function(require, module, exports) {
'use strict';
var objToString = Object.prototype.toString;
// TODO: Move to lib
var existy = function(val) {
return val != null;
};
// TODO: Move to lib
var isArray = function(val) {
return objToString.call(val) === '[object Array]';
};
// TODO: Move to lib
var isString = function(val) {
return typeof val === 'string' || objToString.call(val) === '[object String]';
};
// TODO: Move to lib
var isObject = function(val) {
return val != null && typeof val === 'object';
};
/**
* Returns a copy of the new `object` containing only the specified properties.
*
* @name pick
* @api public
* @category Object
* @see {@link omit}
* @param {Array.<string>|string} props The property or properties to keep.
* @param {Object} object The object to iterate over.
* @return {Object} A new object containing only the specified properties from `object`.
* @example
* var person = { name: 'Tim', occupation: 'enchanter', fears: 'rabbits' };
*
* pick('name', person);
* //=> { name: 'Tim' }
*
* pick(['name', 'fears'], person);
* //=> { name: 'Tim', fears: 'rabbits' }
*/
var pick = function pick(props, object) {
if (!existy(object) || !isObject(object)) {
return {};
}
if (isString(props)) {
props = [props];
}
if (!isArray(props)) {
props = [];
}
var result = {};
for (var i = 0; i < props.length; i += 1) {
if (isString(props[i]) && props[i] in object) {
result[props[i]] = object[props[i]];
}
}
return result;
};
/**
* Exports.
*/
module.exports = pick;
}, {}],
201: [function(require, module, exports) {
/**
* prevent default on the given `e`.
*
* examples:
*
* anchor.onclick = prevent;
* anchor.onclick = function(e){
* if (something) return prevent(e);
* };
*
* @param {Event} e
*/
module.exports = function(e){
e = e || window.event
return e.preventDefault
? e.preventDefault()
: e.returnValue = false;
};
}, {}],
202: [function(require, module, exports) {
/**
* Module dependencies.
*/
var encode = encodeURIComponent;
var decode = decodeURIComponent;
var trim = require('trim');
var type = require('type');
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
if ('?' == str.charAt(0)) str = str.slice(1);
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
var key = decode(parts[0]);
var m;
if (m = /(\w+)\[(\d+)\]/.exec(key)) {
obj[m[1]] = obj[m[1]] || [];
obj[m[1]][m[2]] = decode(parts[1]);
continue;
}
obj[parts[0]] = null == parts[1]
? ''
: decode(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
var value = obj[key];
if ('array' == type(value)) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
}
continue;
}
pairs.push(encode(key) + '=' + encode(obj[key]));
}
return pairs.join('&');
};
}, {"trim":126,"type":7}],
203: [function(require, module, exports) {
/**
* Module Dependencies.
*/
var debug = require('debug')('analytics.js:normalize');
var indexof = require('component/indexof');
var defaults = require('defaults');
var map = require('component/map');
var each = require('each');
var is = require('is');
/**
* HOP.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `normalize`
*/
module.exports = normalize;
/**
* Toplevel properties.
*/
var toplevel = [
'integrations',
'anonymousId',
'timestamp',
'context'
];
/**
* Normalize `msg` based on integrations `list`.
*
* @param {Object} msg
* @param {Array} list
* @return {Function}
*/
function normalize(msg, list){
var lower = map(list, function(s){ return s.toLowerCase(); });
var opts = msg.options || {};
var integrations = opts.integrations || {};
var providers = opts.providers || {};
var context = opts.context || {};
var ret = {};
debug('<-', msg);
// integrations.
each(opts, function(key, value){
if (!integration(key)) return;
if (!has.call(integrations, key)) integrations[key] = value;
delete opts[key];
});
// providers.
delete opts.providers;
each(providers, function(key, value){
if (!integration(key)) return;
if (is.object(integrations[key])) return;
if (has.call(integrations, key) && 'boolean' == typeof providers[key]) return;
integrations[key] = value;
});
// move all toplevel options to msg
// and the rest to context.
each(opts, function(key){
if (~indexof(toplevel, key)) {
ret[key] = opts[key];
} else {
context[key] = opts[key];
}
});
// cleanup
delete msg.options;
ret.integrations = integrations;
ret.context = context;
ret = defaults(ret, msg);
debug('->', ret);
return ret;
function integration(name){
return !! (~indexof(list, name)
|| 'all' == name.toLowerCase()
|| ~indexof(lower, name.toLowerCase()));
}
}
}, {"debug":190,"component/indexof":116,"defaults":97,"component/map":210,"each":4,"is":91}],
210: [function(require, module, exports) {
/**
* Module dependencies.
*/
var toFunction = require('to-function');
/**
* Map the given `arr` with callback `fn(val, i)`.
*
* @param {Array} arr
* @param {Function} fn
* @return {Array}
* @api public
*/
module.exports = function(arr, fn){
var ret = [];
fn = toFunction(fn);
for (var i = 0; i < arr.length; ++i) {
ret.push(fn(arr[i], i));
}
return ret;
};
}, {"to-function":174}],
206: [function(require, module, exports) {
var debug = require('debug')('analytics:user');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
var cookie = require('./cookie');
var uuid = require('uuid');
var rawCookie = require('cookie');
/**
* User defaults
*/
User.defaults = {
persist: true,
cookie: {
key: 'ajs_user_id',
oldKey: 'ajs_user'
},
localStorage: {
key: 'ajs_user_traits'
}
};
/**
* Initialize a new `User` with `options`.
*
* @param {Object} options
*/
function User (options) {
this.defaults = User.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(User, Entity);
/**
* Set / get the user id.
*
* When the user id changes, the method will
* reset his anonymousId to a new one.
*
* Example:
*
* // didn't change because the user didn't have previous id.
* anonId = user.anonymousId();
* user.id('foo');
* assert.equal(anonId, user.anonymousId());
*
* // didn't change because the user id changed to null.
* anonId = user.anonymousId();
* user.id('foo');
* user.id(null);
* assert.equal(anonId, user.anonymousId());
*
* // change because the user had previous id.
* anonId = user.anonymousId();
* user.id('foo');
* user.id('baz'); // triggers change
* user.id('baz'); // no change
* assert.notEqual(anonId, user.anonymousId());
*
* @param {String} id
* @return {Mixed}
*/
User.prototype.id = function(id){
var prev = this._getId();
var ret = Entity.prototype.id.apply(this, arguments);
if (null == prev) return ret;
if (prev != id && id) this.anonymousId(null);
return ret;
};
/**
* Set / get / remove anonymousId.
*
* @param {String} anonId
* @return {String|User}
*/
User.prototype.anonymousId = function(anonId){
var store = this.storage();
// set / remove
if (arguments.length) {
store.set('ajs_anonymous_id', anonId);
return this;
}
// new
if (anonId = store.get('ajs_anonymous_id')) {
return anonId;
}
// old - it is not stringified so we use the raw cookie.
if (anonId = rawCookie('_sio')) {
anonId = anonId.split('----')[0];
store.set('ajs_anonymous_id', anonId);
store.remove('_sio');
return anonId;
}
// empty
anonId = uuid();
store.set('ajs_anonymous_id', anonId);
return store.get('ajs_anonymous_id');
};
/**
* Remove anonymous id on logout too.
*/
User.prototype.logout = function(){
Entity.prototype.logout.call(this);
this.anonymousId(null);
};
/**
* Load saved user `id` or `traits` from storage.
*/
User.prototype.load = function () {
if (this._loadOldCookie()) return;
Entity.prototype.load.call(this);
};
/**
* BACKWARDS COMPATIBILITY: Load the old user from the cookie.
*
* @return {Boolean}
* @api private
*/
User.prototype._loadOldCookie = function () {
var user = cookie.get(this._options.cookie.oldKey);
if (!user) return false;
this.id(user.id);
this.traits(user.traits);
cookie.remove(this._options.cookie.oldKey);
return true;
};
/**
* Expose the user singleton.
*/
module.exports = bind.all(new User());
/**
* Expose the `User` constructor.
*/
module.exports.User = User;
}, {"debug":190,"./entity":207,"inherit":208,"bind":194,"./cookie":195,"uuid":184,"cookie":183}],
5: [function(require, module, exports) {
module.exports = {
"name": "analytics",
"version": "2.8.10",
"main": "analytics.js",
"dependencies": {},
"devDependencies": {}
};
}, {}]}, {}, {"1":""})
); |
src/containers/DevTools/DevTools.js | soupnasty/techheroes-web | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-H"
changePositionKey="ctrl-Q">
<LogMonitor />
</DockMonitor>
);
|
addons/themes/big-picture/layouts/Single.js | rendact/rendact | import $ from 'jquery'
import React from 'react';
import gql from 'graphql-tag';
import {graphql} from 'react-apollo';
import moment from 'moment';
import {Link} from 'react-router';
import scrollToElement from 'scroll-to-element';
class Single extends React.Component {
constructor(props){
super(props)
this.handleHideIntro = this.handleHideIntro.bind(this)
this.state = {
intro: true,
}
}
componentDidMount(){
require('../assets/css/main.css')
window.addEventListener("scroll", this.handleHideIntro)
}
componentWillUnmount(){
window.removeEventListener("scroll", this.handleHideIntro)
}
handleHideIntro(e){
/*
* hide intro when window.pageYOffset => header.height
*/
let header = document.getElementById("header")
let headerRect = header.getBoundingClientRect()
if (window.pageYOffset >= headerRect.height - 10){
this.setState({intro: false})
} else {
this.setState({intro: true})
}
}
handleScrolly(e){
scrollToElement("#inti", {
duration: 1500,
offset: 0,
ease: 'in-sine'
})
}
render(){
let {
postData,
theConfig,
data,
thePagination,
loadDone,
isHome
} = this.props
return (
<div>
<header id="header">
<h1><Link to={"/"}>{theConfig?theConfig.name:"Rendact"}</Link></h1>
<nav>
{this.props.theMenu()}
</nav>
</header>
<section id="intro" className={this.props.intro?"main style1 dark fullscreen inactive":"main style1 dark fullscreen"}>
<div className="content">
<header>
<h2>{theConfig?theConfig.name:"Rendact"}</h2>
</header>
<p>{theConfig?theConfig.tagline:"Hello, you are in Rendact"}.</p>
<footer>
<a href="#" className="button style2 down" onClick={this.handleScrolly}>More</a>
</footer>
</div>
</section>
{postData &&
<section id="inti" className="main style2 right dark fullscreen posts "
style={{backgroundImage: `url(${postData.imageFeatured ? postData.imageFeatured.blobUrl: require('images/logo-128.png')})`}} >
<div className="content box style2">
<header>
<h2>{postData.title && postData.title}</h2>
</header>
<p dangerouslySetInnerHTML={{__html: postData.content ? postData.content :""}} />
</div>
</section>
}
<section id="contact" className="main style3 secondary">
<div className="content">
<div className="row">
{this.props.footerWidgets &&
this.props.footerWidgets.map((fw, idx) =><div className="box">{fw}</div>)}
</div>
</div>
</section>
<footer id="footer">
<ul className="actions">
<li><a href="#" className="icon fa-twitter"><span className="label">Twitter</span></a></li>
<li><a href="#" className="icon fa-facebook"><span className="label">Facebook</span></a></li>
<li><a href="#" className="icon fa-instagram"><span className="label">Instagram</span></a></li>
<li><a href="#" className="icon fa-linkedin"><span className="label">LinkedIn</span></a></li>
<li><a href="#" className="icon fa-dribbble"><span className="label">Dribbble</span></a></li>
<li><a href="#" className="icon fa-pinterest"><span className="label">Pinterest</span></a></li>
</ul>
<ul className="menu">
<li>© Rendact</li><li>Design: <a href="https://html5up.net">HTML5 UP</a></li>
</ul>
</footer>
</div>
)
}
}
export default Single; |
ajax/libs/ScrollMagic/1.3.0/jquery.scrollmagic.js | marxo/cdnjs | /*
ScrollMagic v1.3.0
The jQuery plugin for doing magical scroll interactions.
(c) 2014 Jan Paepke (@janpaepke)
License & Info: http://janpaepke.github.io/ScrollMagic
Inspired by and partially based on SUPERSCROLLORAMA by John Polacek (@johnpolacek)
http://johnpolacek.github.com/superscrollorama/
Powered by the Greensock Tweening Platform (GSAP): http://www.greensock.com/js
Greensock License info at http://www.greensock.com/licensing/
*/
/**
@overview ##Info
@version 1.3.0
@license Dual licensed under MIT license and GPL.
@author Jan Paepke - [email protected]
@todo: enhancement: remove dependencies and move to plugins -> 2.0
@todo: bug: when cascading pins (pinning one element multiple times) and later removing them without reset, positioning errors occur.
@todo: bug: having multiple scroll directions with cascaded pins doesn't work (one scroll vertical, one horizontal)
@todo: feature: optimize performance on debug plugin (huge drawbacks, when using many scenes)
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery', 'TweenMax', 'TimelineMax'], factory);
} else {
// Browser globals
var sm = factory(root.jQuery, root.TweenMax, root.TimelineMax);
root.ScrollMagic = sm.Controller;
root.ScrollScene = sm.Scene;
}
}(this, function ($, TweenMax, TimelineMax) {
/**
* The main class that is needed once per scroll container.
*
* @class
* @global
*
* @example
* // basic initialization
* var controller = new ScrollMagic();
*
* // passing options
* var controller = new ScrollMagic({container: "#myContainer", loglevel: 3});
*
* @param {object} [options] - An object containing one or more options for the controller.
* @param {(string|object)} [options.container=window] - A selector, DOM object or a jQuery object that references the main container for scrolling.
* @param {boolean} [options.vertical=true] - Sets the scroll mode to vertical (`true`) or horizontal (`false`) scrolling.
* @param {object} [options.globalSceneOptions={}] - These options will be passed to every Scene that is added to the controller using the addScene method. For more information on Scene options see {@link ScrollScene}.
* @param {number} [options.loglevel=2] Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic.
** `0` => silent
** `1` => errors
** `2` => errors, warnings
** `3` => errors, warnings, debuginfo
* @param {boolean} [options.refreshInterval=100] - Some changes don't call events by default, like changing the container size or moving a scene trigger element.
This interval polls these parameters to fire the necessary events.
If you don't use custom containers, trigger elements or have static layouts, where the positions of the trigger elements don't change, you can set this to 0 disable interval checking and improve performance.
*
*/
var ScrollMagic = function(options) {
/*
* ----------------------------------------------------------------
* settings
* ----------------------------------------------------------------
*/
var
NAMESPACE = "ScrollMagic",
DEFAULT_OPTIONS = {
container: window,
vertical: true,
globalSceneOptions: {},
loglevel: 2,
refreshInterval: 100
};
/*
* ----------------------------------------------------------------
* private vars
* ----------------------------------------------------------------
*/
var
ScrollMagic = this,
_options = $.extend({}, DEFAULT_OPTIONS, options),
_sceneObjects = [],
_updateScenesOnNextCycle = false, // can be boolean (true => all scenes) or an array of scenes to be updated
_scrollPos = 0,
_scrollDirection = "PAUSED",
_isDocument = true,
_viewPortSize = 0,
_enabled = true,
_updateCycle,
_refreshInterval;
/*
* ----------------------------------------------------------------
* private functions
* ----------------------------------------------------------------
*/
/**
* Internal constructor function of ScrollMagic
* @private
*/
var construct = function () {
ScrollMagic.version = ScrollMagic.constructor.version;
$.each(_options, function (key, value) {
if (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
log(2, "WARNING: Unknown option \"" + key + "\"");
delete _options[key];
}
});
_options.container = $(_options.container).first();
// check ScrollContainer
if (_options.container.length === 0) {
log(1, "ERROR creating object " + NAMESPACE + ": No valid scroll container supplied");
throw NAMESPACE + " init failed."; // cancel
}
_isDocument = !$.contains(document, _options.container.get(0));
// prevent bubbling of fake resize event to window
if (!_isDocument) {
_options.container.on('resize', function ( e ) {
e.stopPropagation();
});
}
// update container size immediately
_viewPortSize = _options.vertical ? _options.container.height() : _options.container.width();
// set event handlers
_options.container.on("scroll resize", onChange);
_options.refreshInterval = parseInt(_options.refreshInterval);
if (_options.refreshInterval > 0) {
_refreshInterval = window.setInterval(refresh, _options.refreshInterval);
}
// start checking for changes
_updateCycle = animationFrameCallback(updateScenes);
log(3, "added new " + NAMESPACE + " controller (v" + ScrollMagic.version + ")");
};
/**
* Default function to get scroll pos - overwriteable using `ScrollMagic.scrollPos(newFunction)`
* @private
*/
var getScrollPos = function () {
return _options.vertical ? _options.container.scrollTop() : _options.container.scrollLeft();
};
/**
* Default function to set scroll pos - overwriteable using `ScrollMagic.scrollTo(newFunction)`
* @private
*/
var setScrollPos = function (pos) {
if (_options.vertical) {
_options.container.scrollTop(pos);
} else {
_options.container.scrollLeft(pos);
}
};
/**
* Handle updates in cycles instead of on scroll (performance)
* @private
*/
var updateScenes = function () {
_updateCycle = animationFrameCallback(updateScenes);
if (_enabled && _updateScenesOnNextCycle) {
var
scenesToUpdate = $.isArray(_updateScenesOnNextCycle) ? _updateScenesOnNextCycle : _sceneObjects.slice(0),
oldScrollPos = _scrollPos;
// update scroll pos & direction
_scrollPos = ScrollMagic.scrollPos();
var deltaScroll = _scrollPos - oldScrollPos;
_scrollDirection = (deltaScroll === 0) ? "PAUSED" : (deltaScroll > 0) ? "FORWARD" : "REVERSE";
if (deltaScroll < 0) { // reverse order if scrolling reverse
scenesToUpdate.reverse();
}
// update scenes
$.each(scenesToUpdate, function (index, scene) {
log(3, "updating Scene " + (index + 1) + "/" + scenesToUpdate.length + " (" + _sceneObjects.length + " total)");
scene.update(true);
});
if (scenesToUpdate.length === 0 && _options.loglevel >= 3) {
log(3, "updating 0 Scenes (nothing added to controller)");
}
_updateScenesOnNextCycle = false;
}
};
/**
* Handles Container changes
* @private
*/
var onChange = function (e) {
if (e.type == "resize") {
_viewPortSize = _options.vertical ? _options.container.height() : _options.container.width();
}
_updateScenesOnNextCycle = true;
};
var refresh = function () {
if (!_isDocument) {
// simulate resize event. Only works for viewport relevant param
if (_viewPortSize != (_options.vertical ? _options.container.height() : _options.container.width())) {
_options.container.trigger("resize");
}
}
$.each(_sceneObjects, function (index, scene) {// refresh all scenes
scene.refresh();
});
};
/**
* Send a debug message to the console.
* @private
*
* @param {number} loglevel - The loglevel required to initiate output for the message.
* @param {...mixed} output - One or more variables that should be passed to the console.
*/
var log = function (loglevel, output) {
if (_options.loglevel >= loglevel) {
var
prefix = "(" + NAMESPACE + ") ->",
args = Array.prototype.splice.call(arguments, 1);
args.unshift(loglevel, prefix);
debug.apply(window, args);
}
};
/**
* Sort scenes in ascending order of their start offset.
* @private
*
* @param {array} ScrollScenesArray - an array of ScrollScenes that should be sorted
* @return {array} The sorted array of ScrollScenes.
*/
var sortScenes = function (ScrollScenesArray) {
if (ScrollScenesArray.length <= 1) {
return ScrollScenesArray;
} else {
var scenes = ScrollScenesArray.slice(0);
scenes.sort(function(a, b) {
return a.scrollOffset() > b.scrollOffset() ? 1 : -1;
});
return scenes;
}
};
/*
* ----------------------------------------------------------------
* public functions
* ----------------------------------------------------------------
*/
/**
* Add one ore more scene(s) to the controller.
* This is the equivalent to `ScrollScene.addTo(controller)`.
* @public
* @example
* // with a previously defined scene
* controller.addScene(scene);
*
* // with a newly created scene.
* controller.addScene(new ScrollScene({duration : 0}));
*
* // adding multiple scenes
* controller.addScene([scene, scene2, new ScrollScene({duration : 0})]);
*
* @param {(ScrollScene|array)} ScrollScene - ScrollScene or Array of ScrollScenes to be added to the controller.
* @return {ScrollMagic} Parent object for chaining.
*/
this.addScene = function (newScene) {
if ($.isArray(newScene)) {
$.each(newScene, function (index, scene) {
ScrollMagic.addScene(scene);
});
} else if (newScene instanceof ScrollScene) {
if (newScene.parent() != ScrollMagic) {
newScene.addTo(ScrollMagic);
} else if ($.inArray(newScene, _sceneObjects) < 0){
// new scene
_sceneObjects.push(newScene); // add to array
_sceneObjects = sortScenes(_sceneObjects); // sort
newScene.on("shift." + NAMESPACE + "_sort", function() { // resort whenever scene moves
_sceneObjects = sortScenes(_sceneObjects);
});
// insert Global defaults.
$.each(_options.globalSceneOptions, function (key, value) {
if (newScene[key]) {
newScene[key].call(newScene, value);
}
});
log(3, "added Scene (" + _sceneObjects.length + " total)");
}
} else {
log(1, "ERROR: invalid argument supplied for '.addScene()'");
}
return ScrollMagic;
};
/**
* Remove one ore more scene(s) from the controller.
* This is the equivalent to `ScrollScene.remove()`.
* @public
* @example
* // remove a scene from the controller
* controller.removeScene(scene);
*
* // remove multiple scenes from the controller
* controller.removeScene([scene, scene2, scene3]);
*
* @param {(ScrollScene|array)} ScrollScene - ScrollScene or Array of ScrollScenes to be removed from the controller.
* @returns {ScrollMagic} Parent object for chaining.
*/
this.removeScene = function (ScrollScene) {
if ($.isArray(ScrollScene)) {
$.each(ScrollScene, function (index, scene) {
ScrollMagic.removeScene(scene);
});
} else {
var index = $.inArray(ScrollScene, _sceneObjects);
if (index > -1) {
ScrollScene.off("shift." + NAMESPACE + "_sort");
_sceneObjects.splice(index, 1);
ScrollScene.remove();
log(3, "removed Scene (" + _sceneObjects.length + " total)");
}
}
return ScrollMagic;
};
/**
* Update one ore more scene(s) according to the scroll position of the container.
* This is the equivalent to `ScrollScene.update()`.
* The update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container.
* It then updates the current scene state accordingly (or does nothing, if the state is already correct) – Pins will be set to their correct position and tweens will be updated to their correct progress.
* _**Note:** This method gets called constantly whenever ScrollMagic detects a change. The only application for you is if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._
* @public
* @example
* // update a specific scene on next cycle
* controller.updateScene(scene);
*
* // update a specific scene immediately
* controller.updateScene(scene, true);
*
* // update multiple scenes scene on next cycle
* controller.updateScene([scene1, scene2, scene3]);
*
* @param {ScrollScene} ScrollScene - ScrollScene or Array of ScrollScenes that is/are supposed to be updated.
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle.
This is useful when changing multiple properties of the scene - this way it will only be updated once all new properties are set (updateScenes).
* @return {ScrollMagic} Parent object for chaining.
*/
this.updateScene = function (ScrollScene, immediately) {
if ($.isArray(ScrollScene)) {
$.each(ScrollScene, function (index, scene) {
ScrollMagic.updateScene(scene, immediately);
});
} else {
if (immediately) {
ScrollScene.update(true);
} else {
// prep array for next update cycle
if (!$.isArray(_updateScenesOnNextCycle)) {
_updateScenesOnNextCycle = [];
}
if ($.inArray(ScrollScene, _updateScenesOnNextCycle) == -1) {
_updateScenesOnNextCycle.push(ScrollScene);
}
_updateScenesOnNextCycle = sortScenes(_updateScenesOnNextCycle); // sort
}
}
return ScrollMagic;
};
/**
* Updates the controller params and calls updateScene on every scene, that is attached to the controller.
* See `ScrollMagic.updateScene()` for more information about what this means.
* In most cases you will not need this function, as it is called constantly, whenever ScrollMagic detects a state change event, like resize or scroll.
* The only application for this method is when ScrollMagic fails to detect these events.
* One application is with some external scroll libraries (like iScroll) that move an internal container to a negative offset instead of actually scrolling. In this case the update on the controller needs to be called whenever the child container's position changes.
* For this case there will also be the need to provide a custom function to calculate the correct scroll position. See `ScrollMagic.scrollPos()` for details.
* @public
* @example
* // update the controller on next cycle (saves performance due to elimination of redundant updates)
* controller.update();
*
* // update the controller immediately
* controller.update(true);
*
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance)
* @return {ScrollMagic} Parent object for chaining.
*/
this.update = function (immediately) {
onChange({type: "resize"}); // will update size and set _updateScenesOnNextCycle to true
if (immediately) {
updateScenes();
}
return ScrollMagic;
};
/**
* Scroll to a numeric scroll offset, a DOM element, the start of a scene or provide an alternate method for scrolling.
* For vertical controllers it will change the top scroll offset and for horizontal applications it will change the left offset.
* @public
*
* @since 1.1.0
* @example
* // scroll to an offset of 100
* controller.scrollTo(100);
*
* // scroll to a DOM element
* controller.scrollTo("#anchor");
*
* // scroll to the beginning of a scene
* var scene = new ScrollScene({offset: 200});
* controller.scrollTo(scene);
*
* // define a new scroll position modification function (animate instead of jump)
* controller.scrollTo(function (newScrollPos) {
* $("body").animate({scrollTop: newScrollPos});
* });
*
* @param {mixed} [scrollTarget] - The supplied argument can be one of these types:
* 1. `number` -> The container will scroll to this new scroll offset.
* 2. `string` or `object` -> Can be a selector, a DOM object or a jQuery element.
* The container will scroll to the position of this element.
* 3. `ScrollScene` -> The container will scroll to the start of this scene.
* 4. `function` -> This function will be used as a callback for future scroll position modifications.
* This provides a way for you to change the behaviour of scrolling and adding new behaviour like animation. The callback receives the new scroll position as a parameter and a reference to the container element using `this`.
* _**NOTE:** All other options will still work as expected, using the new function to scroll._
* @returns {ScrollMagic} Parent object for chaining.
*/
this.scrollTo = function (scrollTarget) {
if (scrollTarget instanceof ScrollScene) {
if (scrollTarget.parent() === ScrollMagic) { // check if this controller is the parent
ScrollMagic.scrollTo(scrollTarget.scrollOffset());
} else {
log (2, "scrollTo(): The supplied scene does not belong to this controller. Scroll cancelled.", scrollTarget);
}
} else if ($.type(scrollTarget) === "string" || isDomElement(scrollTarget) || scrollTarget instanceof $) {
var $elm = $(scrollTarget).first();
if ($elm[0]) {
var
param = _options.vertical ? "top" : "left", // which param is of interest ?
containerOffset = getOffset(_options.container), // container position is needed because element offset is returned in relation to document, not in relation to container.
elementOffset = getOffset($elm);
if (!_isDocument) { // container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent
containerOffset[param] -= ScrollMagic.scrollPos();
}
ScrollMagic.scrollTo(elementOffset[param] - containerOffset[param]);
} else {
log (2, "scrollTo(): The supplied element could not be found. Scroll cancelled.", scrollTarget);
}
} else if ($.isFunction(scrollTarget)) {
setScrollPos = scrollTarget;
} else {
setScrollPos.call(_options.container[0], scrollTarget);
}
return ScrollMagic;
};
/**
* **Get** the current scrollPosition or **Set** a new method to calculate it.
* -> **GET**:
* When used as a getter this function will return the current scroll position.
* To get a cached value use ScrollMagic.info("scrollPos"), which will be updated in the update cycle.
* For vertical controllers it will return the top scroll offset and for horizontal applications it will return the left offset.
*
* -> **SET**:
* When used as a setter this method prodes a way to permanently overwrite the controller's scroll position calculation.
* A typical usecase is when the scroll position is not reflected by the containers scrollTop or scrollLeft values, but for example by the inner offset of a child container.
* Moving a child container inside a parent is a commonly used method for several scrolling frameworks, including iScroll.
* By providing an alternate calculation function you can make sure ScrollMagic receives the correct scroll position.
* Please also bear in mind that your function should return y values for vertical scrolls an x for horizontals.
*
* To change the current scroll position please use `ScrollMagic.scrollTo()`.
* @public
*
* @example
* // get the current scroll Position
* var scrollPos = controller.scrollPos();
*
* // set a new scroll position calculation method
* controller.scrollPos(function () {
* return this.info("vertical") ? -$mychildcontainer.y : -$mychildcontainer.x
* });
*
* @param {function} [scrollPosMethod] - The function to be used for the scroll position calculation of the container.
* @returns {(number|ScrollMagic)} Current scroll position or parent object for chaining.
*/
this.scrollPos = function (scrollPosMethod) {
if (!arguments.length) { // get
return getScrollPos.call(ScrollMagic);
} else { // set
if ($.isFunction(scrollPosMethod)) {
getScrollPos = scrollPosMethod;
} else {
log(2, "Provided value for method 'scrollPos' is not a function. To change the current scroll position use 'scrollTo()'.");
}
}
return ScrollMagic;
};
/**
* **Get** all infos or one in particular about the controller.
* @public
* @example
* // returns the current scroll position (number)
* var scrollPos = controller.info("scrollPos");
*
* // returns all infos as an object
* var infos = controller.info();
*
* @param {string} [about] - If passed only this info will be returned instead of an object containing all.
Valid options are:
** `"size"` => the current viewport size of the container
** `"vertical"` => true if vertical scrolling, otherwise false
** `"scrollPos"` => the current scroll position
** `"scrollDirection"` => the last known direction of the scroll
** `"container"` => the container element
** `"isDocument"` => true if container element is the document.
* @returns {(mixed|object)} The requested info(s).
*/
this.info = function (about) {
var values = {
size: _viewPortSize, // contains height or width (in regard to orientation);
vertical: _options.vertical,
scrollPos: _scrollPos,
scrollDirection: _scrollDirection,
container: _options.container,
isDocument: _isDocument
};
if (!arguments.length) { // get all as an object
return values;
} else if (values[about] !== undefined) {
return values[about];
} else {
log(1, "ERROR: option \"" + about + "\" is not available");
return;
}
};
/**
* **Get** or **Set** the current loglevel option value.
* @public
*
* @example
* // get the current value
* var loglevel = controller.loglevel();
*
* // set a new value
* controller.loglevel(3);
*
* @param {number} [newLoglevel] - The new loglevel setting of the ScrollMagic controller. `[0-3]`
* @returns {(number|ScrollMagic)} Current loglevel or parent object for chaining.
*/
this.loglevel = function (newLoglevel) {
if (!arguments.length) { // get
return _options.loglevel;
} else if (_options.loglevel != newLoglevel) { // set
_options.loglevel = newLoglevel;
}
return ScrollMagic;
};
/**
* **Get** or **Set** the current enabled state of the controller.
* This can be used to disable all Scenes connected to the controller without destroying or removing them.
* @public
*
* @example
* // get the current value
* var enabled = controller.enabled();
*
* // disable the controller
* controller.enabled(false);
*
* @param {boolean} [newState] - The new enabled state of the controller `true` or `false`.
* @returns {(boolean|ScrollMagic)} Current enabled state or parent object for chaining.
*/
this.enabled = function (newState) {
if (!arguments.length) { // get
return _enabled;
} else if (_enabled != newState) { // set
_enabled = !!newState;
ScrollMagic.updateScene(_sceneObjects, true);
}
return ScrollMagic;
};
/**
* Destroy the Controller, all Scenes and everything.
* @public
*
* @example
* // without resetting the scenes
* controller = controller.destroy();
*
* // with scene reset
* controller = controller.destroy(true);
*
* @param {boolean} [resetScenes=false] - If `true` the pins and tweens (if existent) of all scenes will be reset.
* @returns {null} Null to unset handler variables.
*/
this.destroy = function (resetScenes) {
window.clearTimeout(_refreshInterval);
var i = _sceneObjects.length;
while (i--) {
_sceneObjects[i].destroy(resetScenes);
}
_options.container.off("scroll resize", onChange);
animationFrameCancelCallback(_updateCycle);
log(3, "destroyed " + NAMESPACE + " (reset: " + (resetScenes ? "true" : "false") + ")");
return null;
};
// INIT
construct();
return ScrollMagic;
};
ScrollMagic.version = "1.3.0"; // version number for browser global
/**
* A ScrollScene defines where the controller should react and how.
*
* @class
* @global
*
* @example
* // create a standard scene and add it to a controller
* new ScrollScene()
* .addTo(controller);
*
* // create a scene with custom options and assign a handler to it.
* var scene = new ScrollScene({
* duration: 100,
* offset: 200,
* triggerHook: "onEnter",
* reverse: false
* });
*
* @param {object} [options] - Options for the Scene. The options can be updated at any time.
Instead of setting the options for each scene individually you can also set them globally in the controller as the controllers `globalSceneOptions` option. The object accepts the same properties as the ones below.
When a scene is added to the controller the options defined using the ScrollScene constructor will be overwritten by those set in `globalSceneOptions`.
* @param {(number|function)} [options.duration=0] - The duration of the scene.
If `0` tweens will auto-play when reaching the scene start point, pins will be pinned indefinetly starting at the start position.
A function retuning the duration value is also supported. Please see `ScrollScene.duration()` for details.
* @param {number} [options.offset=0] - Offset Value for the Trigger Position. If no triggerElement is defined this will be the scroll distance from the start of the page, after which the scene will start.
* @param {(string|object)} [options.triggerElement=null] - Selector, DOM object or jQuery Object that defines the start of the scene. If undefined the scene will start right at the start of the page (unless an offset is set).
* @param {(number|string)} [options.triggerHook="onCenter"] - Can be a number between 0 and 1 defining the position of the trigger Hook in relation to the viewport.
Can also be defined using a string:
** `"onEnter"` => `1`
** `"onCenter"` => `0.5`
** `"onLeave"` => `0`
* @param {boolean} [options.reverse=true] - Should the scene reverse, when scrolling up?
* @param {boolean} [options.tweenChanges=false] - Tweens Animation to the progress target instead of setting it.
Does not affect animations where duration is `0`.
* @param {number} [options.loglevel=2] - Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic.
** `0` => silent
** `1` => errors
** `2` => errors, warnings
** `3` => errors, warnings, debuginfo
*
*/
var ScrollScene = function (options) {
/*
* ----------------------------------------------------------------
* settings
* ----------------------------------------------------------------
*/
var
TRIGGER_HOOK_VALUES = {"onCenter" : 0.5, "onEnter" : 1, "onLeave" : 0},
NAMESPACE = "ScrollScene",
DEFAULT_OPTIONS = {
duration: 0,
offset: 0,
triggerElement: null,
triggerHook: "onCenter",
reverse: true,
tweenChanges: false,
loglevel: 2
};
/*
* ----------------------------------------------------------------
* private vars
* ----------------------------------------------------------------
*/
var
ScrollScene = this,
_options = $.extend({}, DEFAULT_OPTIONS, options),
_state = 'BEFORE',
_progress = 0,
_scrollOffset = {start: 0, end: 0}, // reflects the parent's scroll position for the start and end of the scene respectively
_triggerPos = 0,
_enabled = true,
_durationUpdateMethod,
_parent,
_tween,
_pin,
_pinOptions,
_cssClasses,
_cssClassElm;
// object containing validator functions for various options
var _validate = {
"unknownOptionSupplied" : function () {
$.each(_options, function (key, value) {
if (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
log(2, "WARNING: Unknown option \"" + key + "\"");
delete _options[key];
}
});
},
"duration" : function () {
if ($.isFunction(_options.duration)) {
_durationUpdateMethod = _options.duration;
try {
_options.duration = parseFloat(_durationUpdateMethod());
} catch (e) {
log(1, "ERROR: Invalid return value of supplied function for option \"duration\":", _options.duration);
_durationUpdateMethod = undefined;
_options.duration = DEFAULT_OPTIONS.duration;
}
} else {
_options.duration = parseFloat(_options.duration);
if (!$.isNumeric(_options.duration) || _options.duration < 0) {
log(1, "ERROR: Invalid value for option \"duration\":", _options.duration);
_options.duration = DEFAULT_OPTIONS.duration;
}
}
},
"offset" : function () {
_options.offset = parseFloat(_options.offset);
if (!$.isNumeric(_options.offset)) {
log(1, "ERROR: Invalid value for option \"offset\":", _options.offset);
_options.offset = DEFAULT_OPTIONS.offset;
}
},
"triggerElement" : function () {
if (_options.triggerElement !== null && $(_options.triggerElement).length === 0) {
log(1, "ERROR: Element defined in option \"triggerElement\" was not found:", _options.triggerElement);
_options.triggerElement = DEFAULT_OPTIONS.triggerElement;
}
},
"triggerHook" : function () {
if (!(_options.triggerHook in TRIGGER_HOOK_VALUES)) {
if ($.isNumeric(_options.triggerHook)) {
_options.triggerHook = Math.max(0, Math.min(parseFloat(_options.triggerHook), 1)); // make sure its betweeen 0 and 1
} else {
log(1, "ERROR: Invalid value for option \"triggerHook\": ", _options.triggerHook);
_options.triggerHook = DEFAULT_OPTIONS.triggerHook;
}
}
},
"reverse" : function () {
_options.reverse = !!_options.reverse; // force boolean
},
"tweenChanges" : function () {
_options.tweenChanges = !!_options.tweenChanges; // force boolean
},
"loglevel" : function () {
_options.loglevel = parseInt(_options.loglevel);
if (!$.isNumeric(_options.loglevel) || _options.loglevel < 0 || _options.loglevel > 3) {
var wrongval = _options.loglevel;
_options.loglevel = DEFAULT_OPTIONS.loglevel;
log(1, "ERROR: Invalid value for option \"loglevel\":", wrongval);
}
},
};
/*
* ----------------------------------------------------------------
* private functions
* ----------------------------------------------------------------
*/
/**
* Internal constructor function of ScrollMagic
* @private
*/
var construct = function () {
validateOption();
// event listeners
ScrollScene
.on("change.internal", function (e) {
if (e.what !== "loglevel" && e.what !== "tweenChanges") { // no need for a scene update scene with these options...
if (e.what === "triggerElement") {
updateTriggerElementPosition();
} else if (e.what === "reverse") { // the only property left that may have an impact on the current scene state. Everything else is handled by the shift event.
ScrollScene.update();
}
}
})
.on("shift.internal", function (e) {
updateScrollOffset();
ScrollScene.update(); // update scene to reflect new position
if ((_state === "AFTER" && e.reason === "duration") || (_state === 'DURING' && _options.duration === 0)) {
// if [duration changed after a scene (inside scene progress updates pin position)] or [duration is 0, we are in pin phase and some other value changed].
updatePinState();
}
})
.on("progress.internal", function (e) {
updateTweenProgress();
updatePinState();
})
.on("destroy", function (e) {
e.preventDefault(); // otherwise jQuery would call target.destroy() by default.
});
};
/**
* Send a debug message to the console.
* @private
*
* @param {number} loglevel - The loglevel required to initiate output for the message.
* @param {...mixed} output - One or more variables that should be passed to the console.
*/
var log = function (loglevel, output) {
if (_options.loglevel >= loglevel) {
var
prefix = "(" + NAMESPACE + ") ->",
args = Array.prototype.splice.call(arguments, 1);
args.unshift(loglevel, prefix);
debug.apply(window, args);
}
};
/**
* Checks the validity of a specific or all options and reset to default if neccessary.
* @private
*/
var validateOption = function (check) {
if (!arguments.length) {
check = [];
for (var key in _validate){
check.push(key);
}
} else if (!$.isArray(check)) {
check = [check];
}
$.each(check, function (key, value) {
if (_validate[value]) {
_validate[value]();
}
});
};
/**
* Helper used by the setter/getters for scene options
* @private
*/
var changeOption = function(varname, newval) {
var
changed = false,
oldval = _options[varname];
if (_options[varname] != newval) {
_options[varname] = newval;
validateOption(varname); // resets to default if necessary
changed = oldval != _options[varname];
}
return changed;
};
/**
* Update the start and end scrollOffset of the container.
* The positions reflect what the parent's scroll position will be at the start and end respectively.
* Is called, when:
* - ScrollScene event "change" is called with: offset, triggerHook, duration
* - scroll container event "resize" is called
* - the position of the triggerElement changes
* - the parent changes -> addTo()
* @private
*/
var updateScrollOffset = function () {
_scrollOffset = {start: _triggerPos + _options.offset};
if (_parent && _options.triggerElement) {
// take away triggerHook portion to get relative to top
_scrollOffset.start -= _parent.info("size") * ScrollScene.triggerHook();
}
_scrollOffset.end = _scrollOffset.start + _options.duration;
};
/**
* Updates the duration if set to a dynamic function.
* This method is called when the scene is added to a controller and in regular intervals from the controller through scene.refresh().
*
* @fires {@link ScrollScene.change}, if the duration changed
* @fires {@link ScrollScene.shift}, if the duration changed
*
* @param {boolean} [suppressEvents=false] - If true the shift event will be suppressed.
* @private
*/
var updateDuration = function (suppressEvents) {
// update duration
if (_durationUpdateMethod) {
var varname = "duration";
if (changeOption(varname, _durationUpdateMethod.call(ScrollScene)) && !suppressEvents) { // set
ScrollScene.trigger("change", {what: varname, newval: _options[varname]});
ScrollScene.trigger("shift", {reason: varname});
}
}
};
/**
* Updates the position of the triggerElement, if present.
* This method is called ...
* - ... when the triggerElement is changed
* - ... when the scene is added to a (new) controller
* - ... in regular intervals from the controller through scene.refresh().
*
* @fires {@link ScrollScene.shift}, if the position changed
*
* @param {boolean} [suppressEvents=false] - If true the shift event will be suppressed.
* @private
*/
var updateTriggerElementPosition = function (suppressEvents) {
var elementPos = 0;
if (_parent && _options.triggerElement) {
var
element = $(_options.triggerElement).first(),
controllerInfo = _parent.info(),
containerOffset = getOffset(controllerInfo.container), // container position is needed because element offset is returned in relation to document, not in relation to container.
param = controllerInfo.vertical ? "top" : "left"; // which param is of interest ?
// if parent is spacer, use spacer position instead so correct start position is returned for pinned elements.
while (element.parent().data("ScrollMagicPinSpacer")) {
element = element.parent();
}
var elementOffset = getOffset(element);
if (!controllerInfo.isDocument) { // container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent
containerOffset[param] -= _parent.scrollPos();
}
elementPos = elementOffset[param] - containerOffset[param];
}
var changed = elementPos != _triggerPos;
_triggerPos = elementPos;
if (changed && !suppressEvents) {
ScrollScene.trigger("shift", {reason: "triggerElementPosition"});
}
};
/**
* Update the tween progress.
* @private
*
* @param {number} [to] - If not set the scene Progress will be used. (most cases)
* @return {boolean} true if the Tween was updated.
*/
var updateTweenProgress = function (to) {
if (_tween) {
var progress = (to >= 0 && to <= 1) ? to : _progress;
if (_tween.repeat() === -1) {
// infinite loop, so not in relation to progress
if (_state === "DURING" && _tween.paused()) {
_tween.play();
} else if (_state !== "DURING" && !_tween.paused()) {
_tween.pause();
} else {
return false;
}
} else if (progress != _tween.progress()) { // do we even need to update the progress?
// no infinite loop - so should we just play or go to a specific point in time?
if (_options.duration === 0) {
// play the animation
if (_state === "DURING") { // play from 0 to 1
_tween.play();
} else { // play from 1 to 0
_tween.reverse();
}
} else {
// go to a specific point in time
if (_options.tweenChanges) {
// go smooth
_tween.tweenTo(progress * _tween.duration());
} else {
// just hard set it
_tween.progress(progress).pause();
}
}
} else {
return false;
}
return true;
} else {
return false;
}
};
/**
* Update the pin state.
* @private
*/
var updatePinState = function (forceUnpin) {
if (_pin && _parent) {
var
containerInfo = _parent.info();
if (!forceUnpin && _state === "DURING") { // during scene or if duration is 0 and we are past the trigger
// pinned state
if (_pin.css("position") != "fixed") {
// change state before updating pin spacer (position changes due to fixed collapsing might occur.)
_pin.css("position", "fixed");
// update pin spacer
updatePinSpacerSize();
// add pinned class
_pin.addClass(_pinOptions.pinnedClass);
}
var
fixedPos = getOffset(_pinOptions.spacer, true), // get viewport position of spacer
scrollDistance = _options.reverse || _options.duration === 0 ?
containerInfo.scrollPos - _scrollOffset.start // quicker
: Math.round(_progress * _options.duration * 10)/10; // if no reverse and during pin the position needs to be recalculated using the progress
// remove spacer margin to get real position (in case marginCollapse mode)
fixedPos.top -= parseFloat(_pinOptions.spacer.css("margin-top"));
// add scrollDistance
fixedPos[containerInfo.vertical ? "top" : "left"] += scrollDistance;
// set new values
_pin.css({
top: fixedPos.top,
left: fixedPos.left
});
} else {
// unpinned state
var
newCSS = {
position: _pinOptions.inFlow ? "relative" : "absolute",
top: 0,
left: 0
},
change = _pin.css("position") != newCSS.position;
if (!_pinOptions.pushFollowers) {
newCSS[containerInfo.vertical ? "top" : "left"] = _options.duration * _progress;
} else if (_options.duration > 0) { // only concerns scenes with duration
if (_state === "AFTER" && parseFloat(_pinOptions.spacer.css("padding-top")) === 0) {
change = true; // if in after state but havent updated spacer yet (jumped past pin)
} else if (_state === "BEFORE" && parseFloat(_pinOptions.spacer.css("padding-bottom")) === 0) { // before
change = true; // jumped past fixed state upward direction
}
}
// set new values
_pin.css(newCSS);
if (change) {
// remove pinned class
_pin.removeClass(_pinOptions.pinnedClass);
// update pin spacer if state changed
updatePinSpacerSize();
}
}
}
};
/**
* Update the pin spacer size.
* The size of the spacer needs to be updated whenever the duration of the scene changes, if it is to push down following elements.
* @private
*/
var updatePinSpacerSize = function () {
if (_pin && _parent && _pinOptions.inFlow) { // no spacerresize, if original position is absolute
var
after = (_state === "AFTER"),
before = (_state === "BEFORE"),
during = (_state === "DURING"),
pinned = (_pin.css("position") == "fixed"),
vertical = _parent.info("vertical"),
$spacercontent = _pinOptions.spacer.children().first(), // usually the pined element but can also be another spacer (cascaded pins)
marginCollapse = isMarginCollapseType(_pinOptions.spacer.css("display")),
css = {};
if (marginCollapse) {
css["margin-top"] = before || (during && pinned) ? _pin.css("margin-top") : "auto";
css["margin-bottom"] = after || (during && pinned) ? _pin.css("margin-bottom") : "auto";
} else {
css["margin-top"] = css["margin-bottom"] = "auto";
}
// set new size
// if relsize: spacer -> pin | else: pin -> spacer
if (_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) {
if (pinned) {
if ($(window).width() == _pinOptions.spacer.parent().width()) {
// relative to body
_pin.css("width", _pinOptions.relSize.autoFullWidth ? "100%" : "inherit");
} else {
// not relative to body -> need to calculate
_pin.css("width", _pinOptions.spacer.width());
}
} else {
_pin.css("width", "100%");
}
} else {
// minwidth is needed for cascading pins.
// margin is only included if it's a cascaded pin to resolve an IE9 bug
css["min-width"] = $spacercontent.outerWidth(!$spacercontent.is(_pin));
css.width = pinned ? css["min-width"] : "auto";
}
if (_pinOptions.relSize.height) {
if (pinned) {
if ($(window).height() == _pinOptions.spacer.parent().height()) {
// relative to body
_pin.css("height", "inherit");
} else {
// not relative to body -> need to calculate
_pin.css("height", _pinOptions.spacer.height());
}
} else {
_pin.css("height", "100%");
}
} else {
css["min-height"] = $spacercontent.outerHeight(!marginCollapse); // needed for cascading pins
css.height = pinned ? css["min-height"] : "auto";
}
// add space for duration if pushFollowers is true
if (_pinOptions.pushFollowers) {
css["padding" + (vertical ? "Top" : "Left")] = _options.duration * _progress;
css["padding" + (vertical ? "Bottom" : "Right")] = _options.duration * (1 - _progress);
}
_pinOptions.spacer.css(css);
}
};
/**
* Updates the Pin state (in certain scenarios)
* If the controller container is not the document and we are mid-pin-phase scrolling or resizing the main document can result to wrong pin positions.
* So this function is called on resize and scroll of the document.
* @private
*/
var updatePinInContainer = function () {
if (_parent && _pin && _state === "DURING" && !_parent.info("isDocument")) {
updatePinState();
}
};
/**
* Updates the Pin spacer size state (in certain scenarios)
* If container is resized during pin and relatively sized the size of the pin might need to be updated...
* So this function is called on resize of the container.
* @private
*/
var updateRelativePinSpacer = function () {
if ( _parent && _pin && // well, duh
_state === "DURING" && // element in pinned state?
( // is width or height relatively sized, but not in relation to body? then we need to recalc.
((_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) && $(window).width() != _pinOptions.spacer.parent().width()) ||
(_pinOptions.relSize.height && $(window).height() != _pinOptions.spacer.parent().height())
)
) {
updatePinSpacerSize();
}
};
/**
* Is called, when the mousewhel is used while over a pinned element inside a div container.
* If the scene is in fixed state scroll events would be counted towards the body. This forwards the event to the scroll container.
* @private
*/
var onMousewheelOverPin = function (e) {
if (_parent && _pin && _state === "DURING" && !_parent.info("isDocument")) { // in pin state
e.preventDefault();
_parent.scrollTo(_parent.info("scrollPos") - (e.originalEvent.wheelDelta/3 || -e.originalEvent.detail*30));
}
};
/*
* ----------------------------------------------------------------
* public functions (getters/setters)
* ----------------------------------------------------------------
*/
/**
* **Get** the parent controller.
* @public
* @example
* // get the parent controller of a scene
* var controller = scene.parent();
*
* @returns {ScrollMagic} Parent controller or `undefined`
*/
this.parent = function () {
return _parent;
};
/**
* **Get** or **Set** the duration option value.
* As a setter it also accepts a function returning a numeric value.
* This is particularly useful for responsive setups.
*
* The duration is updated using the supplied function every time `ScrollScene.refresh()` is called, which happens periodically from the controller (see ScrollMagic option `refreshInterval`).
* _**NOTE:** Be aware that it's an easy way to kill performance, if you supply a function that has high CPU demand.
* Even for size and position calculations it is recommended to use a variable to cache the value. (see example)
* This counts double if you use the same function for multiple scenes._
*
* @public
* @example
* // get the current duration value
* var duration = scene.duration();
*
* // set a new duration
* scene.duration(300);
*
* // use a function to automatically adjust the duration to the window height.
* var durationValueCache;
* function getDuration () {
* return durationValueCache;
* }
* function updateDuration (e) {
* durationValueCache = $(window).innerHeight();
* }
* $(window).on("resize", updateDuration); // update the duration when the window size changes
* $(window).triggerHandler("resize"); // set to initial value
* scene.duration(getDuration); // supply duration method
*
* @fires {@link ScrollScene.change}, when used as setter
* @fires {@link ScrollScene.shift}, when used as setter
* @param {(number|function)} [newDuration] - The new duration of the scene.
* @returns {number} `get` - Current scene duration.
* @returns {ScrollScene} `set` - Parent object for chaining.
*/
this.duration = function (newDuration) {
var varname = "duration";
if (!arguments.length) { // get
return _options[varname];
} else {
if (!$.isFunction(newDuration)) {
_durationUpdateMethod = undefined;
}
if (changeOption(varname, newDuration)) { // set
ScrollScene.trigger("change", {what: varname, newval: _options[varname]});
ScrollScene.trigger("shift", {reason: varname});
}
}
return ScrollScene;
};
/**
* **Get** or **Set** the offset option value.
* @public
* @example
* // get the current offset
* var offset = scene.offset();
*
* // set a new offset
* scene.offset(100);
*
* @fires {@link ScrollScene.change}, when used as setter
* @fires {@link ScrollScene.shift}, when used as setter
* @param {number} [newOffset] - The new offset of the scene.
* @returns {number} `get` - Current scene offset.
* @returns {ScrollScene} `set` - Parent object for chaining.
*/
this.offset = function (newOffset) {
var varname = "offset";
if (!arguments.length) { // get
return _options[varname];
} else if (changeOption(varname, newOffset)) { // set
ScrollScene.trigger("change", {what: varname, newval: _options[varname]});
ScrollScene.trigger("shift", {reason: varname});
}
return ScrollScene;
};
/**
* **Get** or **Set** the triggerElement option value.
* Does **not** fire `ScrollScene.shift`, because changing the trigger Element doesn't necessarily mean the start position changes. This will be determined in `ScrollScene.refresh()`, which is automatically triggered.
* @public
* @example
* // get the current triggerElement
* var triggerElement = scene.triggerElement();
*
* // set a new triggerElement using a selector
* scene.triggerElement("#trigger");
* // set a new triggerElement using a jQuery Object
* scene.triggerElement($("#trigger"));
* // set a new triggerElement using a DOM object
* scene.triggerElement(document.getElementById("trigger"));
*
* @fires {@link ScrollScene.change}, when used as setter
* @param {(string|object)} [newTriggerElement] - The new trigger element for the scene.
* @returns {(string|object)} `get` - Current triggerElement.
* @returns {ScrollScene} `set` - Parent object for chaining.
*/
this.triggerElement = function (newTriggerElement) {
var varname = "triggerElement";
if (!arguments.length) { // get
return _options[varname];
} else if (changeOption(varname, newTriggerElement)) { // set
ScrollScene.trigger("change", {what: varname, newval: _options[varname]});
}
return ScrollScene;
};
/**
* **Get** or **Set** the triggerHook option value.
* @public
* @example
* // get the current triggerHook value
* var triggerHook = scene.triggerHook();
*
* // set a new triggerHook using a string
* scene.triggerHook("onLeave");
* // set a new triggerHook using a number
* scene.triggerHook(0.7);
*
* @fires {@link ScrollScene.change}, when used as setter
* @fires {@link ScrollScene.shift}, when used as setter
* @param {(number|string)} [newTriggerHook] - The new triggerHook of the scene. See {@link ScrollScene} parameter description for value options.
* @returns {number} `get` - Current triggerHook (ALWAYS numerical).
* @returns {ScrollScene} `set` - Parent object for chaining.
*/
this.triggerHook = function (newTriggerHook) {
var varname = "triggerHook";
if (!arguments.length) { // get
return $.isNumeric(_options[varname]) ? _options[varname] : TRIGGER_HOOK_VALUES[_options[varname]];
} else if (changeOption(varname, newTriggerHook)) { // set
ScrollScene.trigger("change", {what: varname, newval: _options[varname]});
ScrollScene.trigger("shift", {reason: varname});
}
return ScrollScene;
};
/**
* **Get** or **Set** the reverse option value.
* @public
* @example
* // get the current reverse option
* var reverse = scene.reverse();
*
* // set new reverse option
* scene.reverse(false);
*
* @fires {@link ScrollScene.change}, when used as setter
* @param {boolean} [newReverse] - The new reverse setting of the scene.
* @returns {boolean} `get` - Current reverse option value.
* @returns {ScrollScene} `set` - Parent object for chaining.
*/
this.reverse = function (newReverse) {
var varname = "reverse";
if (!arguments.length) { // get
return _options[varname];
} else if (changeOption(varname, newReverse)) { // set
ScrollScene.trigger("change", {what: varname, newval: _options[varname]});
}
return ScrollScene;
};
/**
* **Get** or **Set** the tweenChanges option value.
* @public
* @example
* // get the current tweenChanges option
* var tweenChanges = scene.tweenChanges();
*
* // set new tweenChanges option
* scene.tweenChanges(true);
*
* @fires {@link ScrollScene.change}, when used as setter
* @param {boolean} [newTweenChanges] - The new tweenChanges setting of the scene.
* @returns {boolean} `get` - Current tweenChanges option value.
* @returns {ScrollScene} `set` - Parent object for chaining.
*/
this.tweenChanges = function (newTweenChanges) {
var varname = "tweenChanges";
if (!arguments.length) { // get
return _options[varname];
} else if (changeOption(varname, newTweenChanges)) { // set
ScrollScene.trigger("change", {what: varname, newval: _options[varname]});
}
return ScrollScene;
};
/**
* **Get** or **Set** the loglevel option value.
* @public
* @example
* // get the current loglevel
* var loglevel = scene.loglevel();
*
* // set new loglevel
* scene.loglevel(3);
*
* @fires {@link ScrollScene.change}, when used as setter
* @param {number} [newLoglevel] - The new loglevel setting of the scene. `[0-3]`
* @returns {number} `get` - Current loglevel.
* @returns {ScrollScene} `set` - Parent object for chaining.
*/
this.loglevel = function (newLoglevel) {
var varname = "loglevel";
if (!arguments.length) { // get
return _options[varname];
} else if (changeOption(varname, newLoglevel)) { // set
ScrollScene.trigger("change", {what: varname, newval: _options[varname]});
}
return ScrollScene;
};
/**
* **Get** the current state.
* @public
* @example
* // get the current state
* var state = scene.state();
*
* @returns {string} `"BEFORE"`, `"DURING"` or `"AFTER"`
*/
this.state = function () {
return _state;
};
/**
* **Get** the trigger position of the scene (including the value of the `offset` option).
* @public
* @example
* // get the scene's trigger position
* var triggerPosition = scene.triggerPosition();
*
* @returns {number} Start position of the scene. Top position value for vertical and left position value for horizontal scrolls.
*/
this.triggerPosition = function () {
var pos = _options.offset; // the offset is the basis
if (_parent) {
// get the trigger position
if (_options.triggerElement) {
// Element as trigger
pos += _triggerPos;
} else {
// return the height of the triggerHook to start at the beginning
pos += _parent.info("size") * ScrollScene.triggerHook();
}
}
return pos;
};
/**
* **Get** the trigger offset of the scene (including the value of the `offset` option).
* @public
* @deprecated Method is deprecated since 1.1.0. You should now use {@link ScrollScene.triggerPosition}
*/
this.triggerOffset = function () {
return ScrollScene.triggerPosition();
};
/**
* **Get** the current scroll offset for the start of the scene.
* Mind, that the scrollOffset is related to the size of the container, if `triggerHook` is bigger than `0` (or `"onLeave"`).
* This means, that resizing the container or changing the `triggerHook` will influence the scene's start offset.
* @public
* @example
* // get the current scroll offset for the start and end of the scene.
* var start = scene.scrollOffset();
* var end = scene.scrollOffset() + scene.duration();
* console.log("the scene starts at", start, "and ends at", end);
*
* @returns {number} The scroll offset (of the container) at which the scene will trigger. Y value for vertical and X value for horizontal scrolls.
*/
this.scrollOffset = function () {
return _scrollOffset.start;
};
/*
* ----------------------------------------------------------------
* public functions (scene modification)
* ----------------------------------------------------------------
*/
/**
* Updates the Scene in the parent Controller to reflect the current state.
* This is the equivalent to `ScrollMagic.updateScene(scene, immediately)`.
* The update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container.
* It then updates the current scene state accordingly (or does nothing, if the state is already correct) – Pins will be set to their correct position and tweens will be updated to their correct progress.
* This means an update doesn't necessarily result in a progress change. The `progress` event will be fired if the progress has indeed changed between this update and the last.
* _**NOTE:** This method gets called constantly whenever ScrollMagic detects a change. The only application for you is if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._
* @public
* @example
* // update the scene on next tick
* scene.update();
*
* // update the scene immediately
* scene.update(true);
*
* @fires ScrollScene.update
*
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance).
* @returns {ScrollScene} Parent object for chaining.
*/
this.update = function (immediately) {
if (_parent) {
if (immediately) {
if (_parent.enabled() && _enabled) {
var
scrollPos = _parent.info("scrollPos"),
newProgress;
if (_options.duration > 0) {
newProgress = (scrollPos - _scrollOffset.start)/(_scrollOffset.end - _scrollOffset.start);
} else {
newProgress = scrollPos >= _scrollOffset.start ? 1 : 0;
}
ScrollScene.trigger("update", {startPos: _scrollOffset.start, endPos: _scrollOffset.end, scrollPos: scrollPos});
ScrollScene.progress(newProgress);
} else if (_pin && _state === "DURING") {
updatePinState(true); // unpin in position
}
} else {
_parent.updateScene(ScrollScene, false);
}
}
return ScrollScene;
};
/**
* Updates dynamic scene variables like the trigger element position or the duration.
* This method is automatically called in regular intervals from the controller. See {@link ScrollMagic} option `refreshInterval`.
*
* You can call it to minimize lag, for example when you intentionally change the position of the triggerElement.
* If you don't it will simply be updated in the next refresh interval of the container, which is usually sufficient.
*
* @public
* @since 1.1.0
* @example
* scene = new ScrollScene({triggerElement: "#trigger"});
*
* // change the position of the trigger
* $("#trigger").css("top", 500);
* // immediately let the scene know of this change
* scene.refresh();
*
* @fires {@link ScrollScene.shift}, if the trigger element position or the duration changed
* @fires {@link ScrollScene.change}, if the duration changed
*
* @returns {ScrollScene} Parent object for chaining.
*/
this.refresh = function () {
updateDuration();
updateTriggerElementPosition();
// update trigger element position
return ScrollScene;
};
/**
* **Get** or **Set** the scene's progress.
* Usually it shouldn't be necessary to use this as a setter, as it is set automatically by scene.update().
* The order in which the events are fired depends on the duration of the scene:
* 1. Scenes with `duration == 0`:
* Scenes that have no duration by definition have no ending. Thus the `end` event will never be fired.
* When the trigger position of the scene is passed the events are always fired in this order:
* `enter`, `start`, `progress` when scrolling forward
* and
* `progress`, `start`, `leave` when scrolling in reverse
* 2. Scenes with `duration > 0`:
* Scenes with a set duration have a defined start and end point.
* When scrolling past the start position of the scene it will fire these events in this order:
* `enter`, `start`, `progress`
* When continuing to scroll and passing the end point it will fire these events:
* `progress`, `end`, `leave`
* When reversing through the end point these events are fired:
* `enter`, `end`, `progress`
* And when continuing to scroll past the start position in reverse it will fire:
* `progress`, `start`, `leave`
* In between start and end the `progress` event will be called constantly, whenever the progress changes.
*
* In short:
* `enter` events will always trigger **before** the progress update and `leave` envents will trigger **after** the progress update.
* `start` and `end` will always trigger at their respective position.
*
* Please review the event descriptions for details on the events and the event object that is passed to the callback.
*
* @public
* @example
* // get the current scene progress
* var progress = scene.progress();
*
* // set new scene progress
* scene.progress(0.3);
*
* @fires {@link ScrollScene.enter}, when used as setter
* @fires {@link ScrollScene.start}, when used as setter
* @fires {@link ScrollScene.progress}, when used as setter
* @fires {@link ScrollScene.end}, when used as setter
* @fires {@link ScrollScene.leave}, when used as setter
*
* @param {number} [progress] - The new progress value of the scene `[0-1]`.
* @returns {number} `get` - Current scene progress.
* @returns {ScrollScene} `set` - Parent object for chaining.
*/
this.progress = function (progress) {
if (!arguments.length) { // get
return _progress;
} else { // set
var
doUpdate = false,
oldState = _state,
scrollDirection = _parent ? _parent.info("scrollDirection") : 'PAUSED',
reverseOrForward = _options.reverse || progress >= _progress;
if (_options.duration === 0) {
// zero duration scenes
doUpdate = _progress != progress;
_progress = progress < 1 && reverseOrForward ? 0 : 1;
_state = _progress === 0 ? 'BEFORE' : 'DURING';
} else {
// scenes with start and end
if (progress <= 0 && _state !== 'BEFORE' && reverseOrForward) {
// go back to initial state
_progress = 0;
_state = 'BEFORE';
doUpdate = true;
} else if (progress > 0 && progress < 1 && reverseOrForward) {
_progress = progress;
_state = 'DURING';
doUpdate = true;
} else if (progress >= 1 && _state !== 'AFTER') {
_progress = 1;
_state = 'AFTER';
doUpdate = true;
} else if (_state === 'DURING' && !reverseOrForward) {
updatePinState(); // in case we scrolled backwards mid-scene and reverse is disabled => update the pin position, so it doesn't move back as well.
}
}
if (doUpdate) {
// fire events
var
eventVars = {progress: _progress, state: _state, scrollDirection: scrollDirection},
stateChanged = _state != oldState;
var trigger = function (eventName) { // tmp helper to simplify code
ScrollScene.trigger(eventName, eventVars);
};
if (stateChanged) { // enter events
if (oldState !== 'DURING') {
trigger("enter");
trigger(oldState === 'BEFORE' ? "start" : "end");
}
}
trigger("progress");
if (stateChanged) { // leave events
if (_state !== 'DURING') {
trigger(_state === 'BEFORE' ? "start" : "end");
trigger("leave");
}
}
}
return ScrollScene;
}
};
/**
* Add a tween to the scene.
* If you want to add multiple tweens, wrap them into one TimelineMax object and add it.
* The duration of the tween is streched to the scroll duration of the scene, unless the scene has a duration of `0`.
* @public
* @example
* // add a single tween
* scene.setTween(TweenMax.to("obj"), 1, {x: 100});
*
* // add multiple tweens, wrapped in a timeline.
* var timeline = new TimelineMax();
* var tween1 = TweenMax.from("obj1", 1, {x: 100});
* var tween2 = TweenMax.to("obj2", 1, {y: 100});
* timeline
* .add(tween1)
* .add(tween2);
* scene.addTween(timeline);
*
* @param {object} TweenObject - A TweenMax, TweenLite, TimelineMax or TimelineLite object that should be animated in the scene.
* @returns {ScrollScene} Parent object for chaining.
*/
this.setTween = function (TweenObject) {
if (!TimelineMax) {
log(1, "ERROR: TimelineMax wasn't found. Please make sure GSAP is loaded before ScrollMagic or use asynchronous loading.");
return ScrollScene;
}
if (_tween) { // kill old tween?
ScrollScene.removeTween();
}
try {
// wrap Tween into a TimelineMax Object to include delay and repeats in the duration and standardize methods.
_tween = new TimelineMax({smoothChildTiming: true})
.add(TweenObject)
.pause();
} catch (e) {
log(1, "ERROR calling method 'setTween()': Supplied argument is not a valid TweenObject");
} finally {
// some properties need to be transferred it to the wrapper, otherwise they would get lost.
if (TweenObject.repeat && TweenObject.repeat() === -1) {// TweenMax or TimelineMax Object?
_tween.repeat(-1);
_tween.yoyo(TweenObject.yoyo());
}
}
// Some tween validations and debugging helpers
// check if there are position tweens defined for the trigger and warn about it :)
if (_tween && _parent && _options.triggerElement && _options.loglevel >= 2) {// parent is needed to know scroll direction.
var
triggerTweens = _tween.getTweensOf($(_options.triggerElement)),
vertical = _parent.info("vertical");
$.each(triggerTweens, function (index, value) {
var
tweenvars = value.vars.css || value.vars,
condition = vertical ? (tweenvars.top !== undefined || tweenvars.bottom !== undefined) : (tweenvars.left !== undefined || tweenvars.right !== undefined);
if (condition) {
log(2, "WARNING: Tweening the position of the trigger element affects the scene timing and should be avoided!");
return false;
}
});
}
// warn about tween overwrites, when an element is tweened multiple times
if (parseFloat(TweenLite.version) >= 1.14) { // onOverwrite only present since GSAP v1.14.0
var
list = _tween.getChildren(true, true, false), // get all nested tween objects
newCallback = function () {
log(2, "WARNING: tween was overwritten by another. To learn how to avoid this issue see here: https://github.com/janpaepke/ScrollMagic/wiki/WARNING:-tween-was-overwritten-by-another");
};
for (var i=0, thisTween, oldCallback; i<list.length; i++) {
/*jshint loopfunc: true */
thisTween = list[i];
if (oldCallback !== newCallback) { // if tweens is added more than once
oldCallback = thisTween.vars.onOverwrite;
thisTween.vars.onOverwrite = function () {
if (oldCallback) {
oldCallback.apply(this, arguments);
}
newCallback.apply(this, arguments);
};
}
}
}
log(3, "added tween");
updateTweenProgress();
return ScrollScene;
};
/**
* Remove the tween from the scene.
* @public
* @example
* // remove the tween from the scene without resetting it
* scene.removeTween();
*
* // remove the tween from the scene and reset it to initial position
* scene.removeTween(true);
*
* @param {boolean} [reset=false] - If `true` the tween will be reset to its initial values.
* @returns {ScrollScene} Parent object for chaining.
*/
this.removeTween = function (reset) {
if (_tween) {
if (reset) {
updateTweenProgress(0);
}
_tween.kill();
_tween = undefined;
log(3, "removed tween (reset: " + (reset ? "true" : "false") + ")");
}
return ScrollScene;
};
/**
* Pin an element for the duration of the tween.
* If the scene duration is 0 the element will only be unpinned, if the user scrolls back past the start position.
* _**NOTE:** The option `pushFollowers` has no effect, when the scene duration is 0._
* @public
* @example
* // pin element and push all following elements down by the amount of the pin duration.
* scene.setPin("#pin");
*
* // pin element and keeping all following elements in their place. The pinned element will move past them.
* scene.setPin("#pin", {pushFollowers: false});
*
* @param {(string|object)} element - A Selector targeting an element, a DOM object or a jQuery object that is supposed to be pinned.
* @param {object} [settings] - settings for the pin
* @param {boolean} [settings.pushFollowers=true] - If `true` following elements will be "pushed" down for the duration of the pin, if `false` the pinned element will just scroll past them.
Ignored, when duration is `0`.
* @param {string} [settings.spacerClass="scrollmagic-pin-spacer"] - Classname of the pin spacer element, which is used to replace the element.
* @param {string} [settings.pinnedClass=""] - Classname that should be added to the pinned element during pin phase (and removed after).
*
* @returns {ScrollScene} Parent object for chaining.
*/
this.setPin = function (element, settings) {
var
defaultSettings = {
pushFollowers: true,
spacerClass: "scrollmagic-pin-spacer",
pinnedClass: ""
};
settings = $.extend({}, defaultSettings, settings);
// validate Element
element = $(element).first();
if (element.length === 0) {
log(1, "ERROR calling method 'setPin()': Invalid pin element supplied.");
return ScrollScene; // cancel
} else if (element.css("position") == "fixed") {
log(1, "ERROR calling method 'setPin()': Pin does not work with elements that are positioned 'fixed'.");
return ScrollScene; // cancel
}
if (_pin) { // preexisting pin?
if (_pin === element) {
// same pin we already have -> do nothing
return ScrollScene; // cancel
} else {
// kill old pin
ScrollScene.removePin();
}
}
_pin = element;
_pin.parent().hide(); // hack start to force jQuery css to return stylesheet values instead of calculated px values.
var
inFlow = _pin.css("position") != "absolute",
pinCSS = _pin.css(["display", "top", "left", "bottom", "right"]),
sizeCSS = _pin.css(["width", "height"]);
_pin.parent().show(); // hack end.
if (sizeCSS.width === "0px" && inFlow && isMarginCollapseType(pinCSS.display)) {
// log (2, "WARNING: Your pinned element probably needs a defined width or it might collapse during pin.");
}
if (!inFlow && settings.pushFollowers) {
log(2, "WARNING: If the pinned element is positioned absolutely pushFollowers is disabled.");
settings.pushFollowers = false;
}
// create spacer
var spacer = $("<div></div>")
.addClass(settings.spacerClass)
.css(pinCSS)
.data("ScrollMagicPinSpacer", true)
.css({
position: inFlow ? "relative" : "absolute",
"margin-left": "auto",
"margin-right": "auto",
"box-sizing": "content-box"
});
// set the pin Options
var pinInlineCSS = _pin[0].style;
_pinOptions = {
spacer: spacer,
relSize: { // save if size is defined using % values. if so, handle spacer resize differently...
width: sizeCSS.width.slice(-1) === "%",
height: sizeCSS.height.slice(-1) === "%",
autoFullWidth: sizeCSS.width === "0px" && inFlow && isMarginCollapseType(pinCSS.display)
},
pushFollowers: settings.pushFollowers,
inFlow: inFlow, // stores if the element takes up space in the document flow
origStyle: {
width: pinInlineCSS.width || "",
position: pinInlineCSS.position || "",
top: pinInlineCSS.top || "",
left: pinInlineCSS.left || "",
bottom: pinInlineCSS.bottom || "",
right: pinInlineCSS.right || "",
"box-sizing": pinInlineCSS["box-sizing"] || "",
"-moz-box-sizing": pinInlineCSS["-moz-box-sizing"] || "",
"-webkit-box-sizing": pinInlineCSS["-webkit-box-sizing"] || ""
}, // save old styles (for reset)
pinnedClass: settings.pinnedClass // the class that should be added to the element when pinned
};
// if relative size, transfer it to spacer and make pin calculate it...
if (_pinOptions.relSize.width) {
spacer.css("width", sizeCSS.width);
}
if (_pinOptions.relSize.height) {
spacer.css("height", sizeCSS.height);
}
// now place the pin element inside the spacer
_pin.before(spacer)
.appendTo(spacer)
// and set new css
.css({
position: inFlow ? "relative" : "absolute",
top: "auto",
left: "auto",
bottom: "auto",
right: "auto"
});
if (_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) {
_pin.css("box-sizing", "border-box");
}
// add listener to document to update pin position in case controller is not the document.
$(window).on("scroll." + NAMESPACE + "_pin resize." + NAMESPACE + "_pin", updatePinInContainer);
// add mousewheel listener to catch scrolls over fixed elements
_pin.on("mousewheel DOMMouseScroll", onMousewheelOverPin);
log(3, "added pin");
// finally update the pin to init
updatePinState();
return ScrollScene;
};
/**
* Remove the pin from the scene.
* @public
* @example
* // remove the pin from the scene without resetting it (the spacer is not removed)
* scene.removePin();
*
* // remove the pin from the scene and reset the pin element to its initial position (spacer is removed)
* scene.removePin(true);
*
* @param {boolean} [reset=false] - If `false` the spacer will not be removed and the element's position will not be reset.
* @returns {ScrollScene} Parent object for chaining.
*/
this.removePin = function (reset) {
if (_pin) {
if (reset || !_parent) { // if there's no parent no progress was made anyway...
_pin.insertBefore(_pinOptions.spacer)
.css(_pinOptions.origStyle);
_pinOptions.spacer.remove();
} else {
if (_state === "DURING") {
updatePinState(true); // force unpin at position
}
}
$(window).off("scroll." + NAMESPACE + "_pin resize." + NAMESPACE + "_pin");
_pin.off("mousewheel DOMMouseScroll", onMousewheelOverPin);
_pin = undefined;
log(3, "removed pin (reset: " + (reset ? "true" : "false") + ")");
}
return ScrollScene;
};
/**
* Define a css class modification while the scene is active.
* When the scene triggers the classes will be added to the supplied element and removed, when the scene is over.
* If the scene duration is 0 the classes will only be removed if the user scrolls back past the start position.
* @public
* @example
* // add the class 'myclass' to the element with the id 'my-elem' for the duration of the scene
* scene.setClassToggle("#my-elem", "myclass");
*
* // add multiple classes to multiple elements defined by the selector '.classChange'
* scene.setClassToggle(".classChange", "class1 class2 class3");
*
* @param {(string|object)} element - A Selector targeting one or more elements, a DOM object or a jQuery object that is supposed to be modified.
* @param {string} classes - One or more Classnames (separated by space) that should be added to the element during the scene.
*
* @returns {ScrollScene} Parent object for chaining.
*/
this.setClassToggle = function (element, classes) {
var $elm = $(element);
if ($elm.length === 0 || $.type(classes) !== "string") {
log(1, "ERROR calling method 'setClassToggle()': Invalid " + ($elm.length === 0 ? "element" : "classes") + " supplied.");
return ScrollScene;
}
_cssClasses = classes;
_cssClassElm = $elm;
ScrollScene.on("enter.internal_class leave.internal_class", function (e) {
_cssClassElm.toggleClass(_cssClasses, e.type === "enter");
});
return ScrollScene;
};
/**
* Remove the class binding from the scene.
* @public
* @example
* // remove class binding from the scene without reset
* scene.removeClassToggle();
*
* // remove class binding and remove the changes it caused
* scene.removeClassToggle(true);
*
* @param {boolean} [reset=false] - If `false` and the classes are currently active, they will remain on the element. If `true` they will be removed.
* @returns {ScrollScene} Parent object for chaining.
*/
this.removeClassToggle = function (reset) {
if (_cssClassElm && reset) {
_cssClassElm.removeClass(_cssClasses);
}
ScrollScene.off("start.internal_class end.internal_class");
_cssClasses = undefined;
_cssClassElm = undefined;
return ScrollScene;
};
/**
* Add the scene to a controller.
* This is the equivalent to `ScrollMagic.addScene(scene)`.
* @public
* @example
* // add a scene to a ScrollMagic controller
* scene.addTo(controller);
*
* @param {ScrollMagic} controller - The controller to which the scene should be added.
* @returns {ScrollScene} Parent object for chaining.
*/
this.addTo = function (controller) {
if (!(controller instanceof ScrollMagic)) {
log(1, "ERROR: supplied argument of 'addTo()' is not a valid ScrollMagic controller");
} else if (_parent != controller) {
// new parent
if (_parent) { // I had a parent before, so remove it...
_parent.removeScene(ScrollScene);
}
_parent = controller;
validateOption();
updateDuration(true);
updateTriggerElementPosition(true);
updateScrollOffset();
updatePinSpacerSize();
_parent.info("container").on("resize." + NAMESPACE, function () {
updateRelativePinSpacer();
if (ScrollScene.triggerHook() > 0) {
ScrollScene.trigger("shift", {reason: "containerSize"});
}
});
log(3, "added " + NAMESPACE + " to controller");
controller.addScene(ScrollScene);
ScrollScene.update();
}
return ScrollScene;
};
/**
* **Get** or **Set** the current enabled state of the scene.
* This can be used to disable this scene without removing or destroying it.
* @public
*
* @example
* // get the current value
* var enabled = scene.enabled();
*
* // disable the scene
* scene.enabled(false);
*
* @param {boolean} [newState] - The new enabled state of the scene `true` or `false`.
* @returns {(boolean|ScrollScene)} Current enabled state or parent object for chaining.
*/
this.enabled = function (newState) {
if (!arguments.length) { // get
return _enabled;
} else if (_enabled != newState) { // set
_enabled = !!newState;
ScrollScene.update(true);
}
return ScrollScene;
};
/**
* Remove the scene from its parent controller.
* This is the equivalent to `ScrollMagic.removeScene(scene)`.
* The scene will not be updated anymore until you readd it to a controller.
* To remove the pin or the tween you need to call removeTween() or removePin() respectively.
* @public
* @example
* // remove the scene from its parent controller
* scene.remove();
*
* @returns {ScrollScene} Parent object for chaining.
*/
this.remove = function () {
if (_parent) {
_parent.info("container").off("resize." + NAMESPACE);
var tmpParent = _parent;
_parent = undefined;
log(3, "removed " + NAMESPACE + " from controller");
tmpParent.removeScene(ScrollScene);
}
return ScrollScene;
};
/**
* Destroy the scene and everything.
* @public
* @example
* // destroy the scene without resetting the pin and tween to their initial positions
* scene = scene.destroy();
*
* // destroy the scene and reset the pin and tween
* scene = scene.destroy(true);
*
* @param {boolean} [reset=false] - If `true` the pin and tween (if existent) will be reset.
* @returns {null} Null to unset handler variables.
*/
this.destroy = function (reset) {
ScrollScene.removeTween(reset);
ScrollScene.removePin(reset);
ScrollScene.removeClassToggle(reset);
ScrollScene.trigger("destroy", {reset: reset});
ScrollScene.remove();
ScrollScene.off("start end enter leave progress change update shift destroy shift.internal change.internal progress.internal");
log(3, "destroyed " + NAMESPACE + " (reset: " + (reset ? "true" : "false") + ")");
return null;
};
/*
* ----------------------------------------------------------------
* EVENTS
* ----------------------------------------------------------------
*/
/**
* Scene start event.
* Fires whenever the scroll position its the starting point of the scene.
* It will also fire when scrolling back up going over the start position of the scene. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback.
*
* For details on this event and the order in which it is fired, please review the {@link ScrollScene.progress} method.
*
* @event ScrollScene.start
*
* @example
* scene.on("start", function (event) {
* alert("Hit start point of scene.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"BEFORE"`, `"DURING"` or `"AFTER"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene end event.
* Fires whenever the scroll position its the ending point of the scene.
* It will also fire when scrolling back up from after the scene and going over its end position. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback.
*
* For details on this event and the order in which it is fired, please review the {@link ScrollScene.progress} method.
*
* @event ScrollScene.end
*
* @example
* scene.on("end", function (event) {
* alert("Hit end point of scene.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"BEFORE"`, `"DURING"` or `"AFTER"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene enter event.
* Fires whenever the scene enters the "DURING" state.
* Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene enters its active scroll timeframe, regardless of the scroll-direction.
*
* For details on this event and the order in which it is fired, please review the {@link ScrollScene.progress} method.
*
* @event ScrollScene.enter
*
* @example
* scene.on("enter", function (event) {
* alert("Entered a scene.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"BEFORE"`, `"DURING"` or `"AFTER"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene leave event.
* Fires whenever the scene's state goes from "DURING" to either "BEFORE" or "AFTER".
* Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene leaves its active scroll timeframe, regardless of the scroll-direction.
*
* For details on this event and the order in which it is fired, please review the {@link ScrollScene.progress} method.
*
* @event ScrollScene.leave
*
* @example
* scene.on("leave", function (event) {
* alert("Left a scene.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"BEFORE"`, `"DURING"` or `"AFTER"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene update event.
* Fires whenever the scene is updated (but not necessarily changes the progress).
*
* @event ScrollScene.update
*
* @example
* scene.on("update", function (event) {
* console.log("Scene updated.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {number} event.startPos - The starting position of the scene (in relation to the conainer)
* @property {number} event.endPos - The ending position of the scene (in relation to the conainer)
* @property {number} event.scrollPos - The current scroll position of the container
*/
/**
* Scene progress event.
* Fires whenever the progress of the scene changes.
*
* For details on this event and the order in which it is fired, please review the {@link ScrollScene.progress} method.
*
* @event ScrollScene.progress
*
* @example
* scene.on("progress", function (event) {
* console.log("Scene progress changed.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"BEFORE"`, `"DURING"` or `"AFTER"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene change event.
* Fires whenvever a property of the scene is changed.
*
* @event ScrollScene.change
*
* @example
* scene.on("change", function (event) {
* console.log("Scene Property \"" + event.what + "\" changed to " + event.newval);
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {string} event.what - Indicates what value has been changed
* @property {mixed} event.newval - The new value of the changed property
*/
/**
* Scene shift event.
* Fires whenvever the start or end **scroll offset** of the scene change.
* This happens explicitely, when one of these values change: `offset`, `duration` or `triggerHook`.
* It will fire implicitly when the `triggerElement` changes, if the new element has a different position (most cases).
* It will also fire implicitly when the size of the container changes and the triggerHook is anything other than `onLeave`.
*
* @event ScrollScene.shift
* @since 1.1.0
*
* @example
* scene.on("shift", function (event) {
* console.log("Scene moved, because the " + event.reason + " has changed.)");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {string} event.reason - Indicates why the scene has shifted
*/
/**
* Scene destroy event.
* Fires whenvever the scene is destroyed.
* This can be used to tidy up custom behaviour used in events.
*
* @event ScrollScene.destroy
* @since 1.1.0
*
* @example
* scene.on("enter", function (event) {
* // add custom action
* $("#my-elem").left("200");
* })
* .on("destroy", function (event) {
* // reset my element to start position
* if (event.reset) {
* $("#my-elem").left("0");
* }
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {ScrollScene} event.target - The ScrollScene object that triggered this event
* @property {boolean} event.reset - Indicates if the destroy method was called with reset `true` or `false`.
*/
/**
* Add one ore more event listener.
* The callback function will be fired at the respective event, and an object containing relevant data will be passed to the callback.
* @public
*
* @example
* function callback (event) {
* console.log("Event fired! (" + event.type + ")");
* }
* // add listeners
* scene.on("change update progress start end enter leave", callback);
*
* @param {string} name - The name or names of the event the callback should be attached to.
* @param {function} callback - A function that should be executed, when the event is dispatched. An event object will be passed to the callback.
* @returns {ScrollScene} Parent object for chaining.
*/
this.on = function (name, callback) {
if ($.isFunction(callback)) {
var names = $.trim(name).toLowerCase()
.replace(/(\w+)\.(\w+)/g, '$1.' + NAMESPACE + '_$2') // add custom namespace, if one is defined
.replace(/( |^)(\w+)(?= |$)/g, '$1$2.' + NAMESPACE ); // add namespace to regulars.
$(ScrollScene).on(names, callback);
} else {
log(1, "ERROR calling method 'on()': Supplied argument is not a valid callback!");
}
return ScrollScene;
};
/**
* Remove one or more event listener.
* @public
*
* @example
* function callback (event) {
* console.log("Event fired! (" + event.type + ")");
* }
* // add listeners
* scene.on("change update", callback);
* // remove listeners
* scene.off("change update", callback);
*
* @param {string} name - The name or names of the event that should be removed.
* @param {function} [callback] - A specific callback function that should be removed. If none is passed all callbacks to the event listener will be removed.
* @returns {ScrollScene} Parent object for chaining.
*/
this.off = function (name, callback) {
var names = $.trim(name).toLowerCase()
.replace(/(\w+)\.(\w+)/g, '$1.' + NAMESPACE + '_$2') // add custom namespace, if one is defined
.replace(/( |^)(\w+)(?= |$)/g, '$1$2.' + NAMESPACE + '$3'); // add namespace to regulars.
$(ScrollScene).off(names, callback);
return ScrollScene;
};
/**
* Trigger an event.
* @public
*
* @example
* this.trigger("change");
*
* @param {string} name - The name of the event that should be triggered.
* @param {object} [vars] - An object containing info that should be passed to the callback.
* @returns {ScrollScene} Parent object for chaining.
*/
this.trigger = function (name, vars) {
log(3, 'event fired:', name, "->", vars);
var event = $.Event($.trim(name).toLowerCase(), vars);
$(ScrollScene).trigger(event);
return ScrollScene;
};
// INIT
construct();
return ScrollScene;
};
/*
* ----------------------------------------------------------------
* global logging functions and making sure no console errors occur
* ----------------------------------------------------------------
*/
var debug = (function (console) {
var loglevels = ["error", "warn", "log"];
if (!console.log) {
console.log = function(){}; // no console log, well - do nothing then...
}
for(var i = 0, method; i<loglevels.length; i++) { // make sure methods for all levels exist.
method = loglevels[i];
if (!console[method]) {
console[method] = console.log; // prefer .log over nothing
}
}
// debugging function
return function (loglevel) {
if (loglevel > loglevels.length || loglevel <= 0) loglevel = loglevels.length;
var now = new Date(),
time = ("0"+now.getHours()).slice(-2) + ":" + ("0"+now.getMinutes()).slice(-2) + ":" + ("0"+now.getSeconds()).slice(-2) + ":" + ("00"+now.getMilliseconds()).slice(-3),
method = loglevels[loglevel-1],
args = Array.prototype.splice.call(arguments, 1),
func = Function.prototype.bind.call(console[method], console);
args.unshift(time);
func.apply(console, args);
};
}(window.console = window.console || {}));
// a helper function that should generally be faster than jQuery.offset() and can also return position in relation to viewport.
var getOffset = function (elem, relativeToViewport) {
var offset = {top: 0, left: 0};
elem = elem[0]; // tmp workaround until jQuery dependency is removed.
if (elem && elem.getBoundingClientRect) { // check if available
var rect = elem.getBoundingClientRect();
offset.top = rect.top;
offset.left = rect.left;
if (!relativeToViewport) { // clientRect is by default relative to viewport...
offset.top += (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0);
offset.left += (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0);
}
}
return offset;
};
var isDomElement = function (o){
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
};
var isMarginCollapseType = function (str) {
return ["block", "flex", "list-item", "table", "-webkit-box"].indexOf(str) > -1;
};
// implementation of requestAnimationFrame
var animationFrameCallback = window.requestAnimationFrame;
var animationFrameCancelCallback = window.cancelAnimationFrame;
// polyfill -> based on https://gist.github.com/paulirish/1579671
(function (window) {
var
lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'],
i;
// try vendor prefixes if the above doesn't work
for (i = 0; !animationFrameCallback && i < vendors.length; ++i) {
animationFrameCallback = window[vendors[i] + 'RequestAnimationFrame'];
animationFrameCancelCallback = window[vendors[i] + 'CancelAnimationFrame'] || window[vendors[i] + 'CancelRequestAnimationFrame'];
}
// fallbacks
if (!animationFrameCallback) {
animationFrameCallback = function (callback) {
var
currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!animationFrameCancelCallback) {
animationFrameCancelCallback = function (id) {
window.clearTimeout(id);
};
}
}(window));
return {
Controller: ScrollMagic,
Scene: ScrollScene,
};
}));
|
src/parser/warrior/arms/modules/features/RageDetails.js | FaideWW/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import Tab from 'interface/others/Tab';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import { formatPercentage } from 'common/format';
import Icon from 'common/Icon';
import ResourceBreakdown from 'parser/shared/modules/resourcetracker/ResourceBreakdown';
import RageTracker from './RageTracker';
class RageDetails extends Analyzer {
static dependencies = {
rageTracker: RageTracker,
};
get wastedPercent() {
return (this.rageTracker.wasted / (this.rageTracker.wasted + this.rageTracker.generated) || 0);
}
get efficiencySuggestionThresholds() {
return {
actual: 1 - this.wastedPercent,
isLessThan: {
minor: 0.95,
average: 0.90,
major: .85,
},
style: 'percentage',
};
}
get suggestionThresholds() {
return {
actual: this.wastedPercent,
isGreaterThan: {
minor: 0.05,
average: 0.1,
major: .15,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(`You wasted ${formatPercentage(this.wastedPercent)}% of your Rage.`)
.icon('spell_nature_reincarnation')
.actual(`${formatPercentage(actual)}% wasted`)
.recommended(`<${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
position={STATISTIC_ORDER.CORE(5)}
icon={<Icon icon="spell_nature_reincarnation" />}
value={`${formatPercentage(this.wastedPercent)} %`}
label="Rage wasted"
tooltip={`${this.rageTracker.wasted} out of ${this.rageTracker.wasted + this.rageTracker.generated} rage wasted.`}
/>
);
}
tab() {
return {
title: 'Rage usage',
url: 'rage-usage',
render: () => (
<Tab>
<ResourceBreakdown
tracker={this.rageTracker}
showSpenders
/>
</Tab>
),
};
}
}
export default RageDetails;
|
examples/00 Chessboard/Tutorial App/index.js | tylercollier/react-dnd-demo | import React, { Component } from 'react';
import Board from './Board';
import { observe } from './Game';
/**
* Unlike the tutorial, export a component so it can be used on the website.
*/
export default class ChessboardTutorialApp extends Component {
constructor(props) {
super(props);
this.unobserve = observe(this.handleChange.bind(this));
}
handleChange(knightPosition) {
const nextState = { knightPosition };
if (this.state) {
this.setState(nextState);
} else {
this.state = nextState;
}
}
componentWillUnmount() {
this.unobserve();
}
render() {
const { knightPosition } = this.state;
return (
<div>
<p>
<b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/00%20Chessboard/Tutorial%20App'>Browse the Source</a></b>
</p>
<p>
This is a sample app you'll build as you work through the <a href='docs-tutorial.html'>tutorial</a>.
</p>
<p>
It illustrates creating the drag sources and the drop targets, using the monitors to query the current drag state, and customizing the drag previews.
</p>
<div style={{
width: 500,
height: 500,
border: '1px solid gray'
}}>
<Board knightPosition={knightPosition} />
</div>
<p>
Make sure to check out the <a href='docs-tutorial.html'>tutorial</a> for step-by-step instructions on building it!
</p>
</div>
);
}
} |
Bonobo.Git.Server/Scripts/jquery-1.4.4-vsdoc.js | dunderburken/Bonobo-Git-Server | /*
* This file has been commented to support Visual Studio Intellisense.
* You should not use this file at runtime inside the browser--it is only
* intended to be used only for design-time IntelliSense. Please use the
* standard jQuery library for all production use.
*
* Comment version: 1.4.4a
*/
/*!
* Note: While Microsoft is not the author of this file, Microsoft is
* offering you a license subject to the terms of the Microsoft Software
* License Terms for Microsoft ASP.NET Model View Controller 3.
* Microsoft reserves all other rights. The notices below are provided
* for informational purposes only and are not the license terms under
* which Microsoft distributed this file.
*
* jQuery JavaScript Library v1.4.4
* http://jquery.com/
*
* Copyright 2010, John Resig
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
*
* Date: Thu Nov 11 19:04:53 2010 -0500
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
/// <summary>
/// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements.
/// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML.
/// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s).
/// 4: $(callback) - A shorthand for $(document).ready().
/// 5: $() - As of jQuery 1.4, if you pass no arguments in to the jQuery() method, an empty jQuery set will be returned.
/// </summary>
/// <param name="selector" type="String">
/// 1: expression - An expression to search with.
/// 2: html - A string of HTML to create on the fly.
/// 3: elements - DOM element(s) to be encapsulated by a jQuery object.
/// 4: callback - The function to execute when the DOM is ready.
/// </param>
/// <param name="context" type="jQuery">
/// 1: context - A DOM Element, Document or jQuery to use as context.
/// </param>
/// <returns type="jQuery" />
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
rwhite = /\s/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Check for non-word characters
rnonword = /\W/,
// Check for digits
rdigit = /\d/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// Has the ready events already been bound?
readyBound = false,
// The functions to execute on DOM ready
readyList = [],
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = "body";
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $("TAG")
} else if ( !context && !rnonword.test( selector ) ) {
this.selector = selector;
this.context = document;
selector = document.getElementsByTagName( selector );
return jQuery.merge( this, selector );
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return jQuery( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.4.4",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
/// <summary>
/// The number of elements currently matched.
/// Part of Core
/// </summary>
/// <returns type="Number" />
return this.length;
},
toArray: function() {
/// <summary>
/// Retrieve all the DOM elements contained in the jQuery set, as an array.
/// </summary>
/// <returns type="Array" />
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 ) {
/// <summary>
/// Access a single matched element. num is used to access the
/// Nth element matched.
/// Part of Core
/// </summary>
/// <returns type="Element" />
/// <param name="num" type="Number">
/// Access the element in the Nth position.
/// </param>
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 ) {
/// <summary>
/// Set the jQuery object to an array of elements, while maintaining
/// the stack.
/// Part of Core
/// </summary>
/// <returns type="jQuery" />
/// <param name="elems" type="Elements">
/// An array of elements
/// </param>
// 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 ) {
/// <summary>
/// Execute a function within the context of every matched element.
/// This means that every time the passed-in function is executed
/// (which is once for every element matched) the 'this' keyword
/// points to the specific element.
/// Additionally, the function, when executed, is passed a single
/// argument representing the position of the element in the matched
/// set.
/// Part of Core
/// </summary>
/// <returns type="jQuery" />
/// <param name="callback" type="Function">
/// A function to execute
/// </param>
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
/// <summary>
/// Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
/// </summary>
/// <param name="fn" type="Function">The function to be executed when the DOM is ready.</param>
// 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 ) {
/// <summary>
/// Reduce the set of matched elements to a single element.
/// The position of the element in the set of matched elements
/// starts at 0 and goes to length - 1.
/// Part of Core
/// </summary>
/// <returns type="jQuery" />
/// <param name="num" type="Number">
/// pos The index of the element that you wish to limit to.
/// </param>
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
},
first: function() {
/// <summary>
/// Reduce the set of matched elements to the first in the set.
/// </summary>
/// <returns type="jQuery" />
return this.eq( 0 );
},
last: function() {
/// <summary>
/// Reduce the set of matched elements to the final one in the set.
/// </summary>
/// <returns type="jQuery" />
return this.eq( -1 );
},
slice: function() {
/// <summary>
/// Selects a subset of the matched elements. Behaves exactly like the built-in Array slice method.
/// </summary>
/// <param name="start" type="Number" integer="true">Where to start the subset (0-based).</param>
/// <param name="end" optional="true" type="Number" integer="true">Where to end the subset (not including the end element itself).
/// If omitted, ends at the end of the selection</param>
/// <returns type="jQuery">The sliced elements</returns>
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
/// <summary>
/// This member is internal.
/// </summary>
/// <private />
/// <returns type="jQuery" />
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
/// <summary>
/// End the most recent 'destructive' operation, reverting the list of matched elements
/// back to its previous state. After an end operation, the list of matched elements will
/// revert to the last state of matched elements.
/// If there was no destructive operation before, an empty set is returned.
/// Part of DOM/Traversing
/// </summary>
/// <returns type="jQuery" />
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() {
/// <summary>
/// Extend one object with one or more others, returning the original,
/// modified, object. This is a great utility for simple inheritance.
/// jQuery.extend(settings, options);
/// var settings = jQuery.extend({}, defaults, options);
/// Part of JavaScript
/// </summary>
/// <param name="target" type="Object">
/// The object to extend
/// </param>
/// <param name="prop1" type="Object">
/// The object that will be merged into the first.
/// </param>
/// <param name="propN" type="Object" optional="true" parameterArray="true">
/// (optional) More objects to merge into the first
/// </param>
/// <returns type="Object" />
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 ) {
/// <summary>
/// Run this function to give control of the $ variable back
/// to whichever library first implemented it. This helps to make
/// sure that jQuery doesn't conflict with the $ object
/// of other libraries.
/// By using this function, you will only be able to access jQuery
/// using the 'jQuery' variable. For example, where you used to do
/// $("div p"), you now must do jQuery("div p").
/// Part of Core
/// </summary>
/// <returns type="undefined" />
window.$ = _$;
if ( deep ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Handle when the DOM is ready
ready: function( wait ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
// A third-party is pushing the ready event forwards
if ( wait === true ) {
jQuery.readyWait--;
}
// Make sure that the DOM is not already loaded
if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
if ( readyList ) {
// Execute all of them
var fn,
i = 0,
ready = readyList;
// Reset the list of functions
readyList = null;
while ( (fn = ready[ i++ ]) ) {
fn.call( document, jQuery );
}
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
}
},
bindReady: function() {
if ( readyBound ) {
return;
}
readyBound = true;
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
/// <summary>
/// Determines if the parameter passed is a function.
/// </summary>
/// <param name="obj" type="Object">The object to check</param>
/// <returns type="Boolean">True if the parameter is a function; otherwise false.</returns>
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
/// <summary>
/// Determine if the parameter passed is an array.
/// </summary>
/// <param name="obj" type="Object">Object to test whether or not it is an array.</param>
/// <returns type="Boolean">True if the parameter is a function; otherwise false.</returns>
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNaN: function( obj ) {
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
/// <summary>
/// Check to see if an object is a plain object (created using "{}" or "new Object").
/// </summary>
/// <param name="obj" type="Object">
/// The object that will be checked to see if it's a plain object.
/// </param>
/// <returns type="Boolean" />
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
/// <summary>
/// Check to see if an object is empty (contains no properties).
/// </summary>
/// <param name="obj" type="Object">
/// The object that will be checked to see if it's empty.
/// </param>
/// <returns type="Boolean" />
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw msg;
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test(data.replace(rvalidescape, "@")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} else {
jQuery.error( "Invalid JSON: " + data );
}
},
noop: function() {
/// <summary>
/// An empty function.
/// </summary>
/// <returns type="Function" />
},
// Evalulates a script in a global context
globalEval: function( data ) {
/// <summary>
/// Internally evaluates a script in a global context.
/// </summary>
/// <private />
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 ) {
/// <summary>
/// Checks whether the specified element has the specified DOM node name.
/// </summary>
/// <param name="elem" type="Element">The element to examine</param>
/// <param name="name" type="String">The node name to check</param>
/// <returns type="Boolean">True if the specified node name matches the node's DOM node name; otherwise false</returns>
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
/// <summary>
/// A generic iterator function, which can be used to seemlessly
/// iterate over both objects and arrays. This function is not the same
/// as $().each() - which is used to iterate, exclusively, over a jQuery
/// object. This function can be used to iterate over anything.
/// The callback has two arguments:the key (objects) or index (arrays) as first
/// the first, and the value as the second.
/// Part of JavaScript
/// </summary>
/// <param name="obj" type="Object">
/// The object, or array, to iterate over.
/// </param>
/// <param name="fn" type="Function">
/// The function that will be executed on every object.
/// </param>
/// <returns type="Object" />
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction(object);
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
/// <summary>
/// Turns anything into a true array. This is an internal method.
/// </summary>
/// <param name="array" type="Object">Anything to turn into an actual Array</param>
/// <returns type="Array" />
/// <private />
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type(array);
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
merge: function( first, second ) {
/// <summary>
/// Merge two arrays together, removing all duplicates.
/// The new array is: All the results from the first array, followed
/// by the unique results from the second array.
/// Part of JavaScript
/// </summary>
/// <returns type="Array" />
/// <param name="first" type="Array">
/// The first array to merge.
/// </param>
/// <param name="second" type="Array">
/// The second array to merge.
/// </param>
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 ) {
/// <summary>
/// Filter items out of an array, by using a filter function.
/// The specified function will be passed two arguments: The
/// current array item and the index of the item in the array. The
/// function must return 'true' to keep the item in the array,
/// false to remove it.
/// });
/// Part of JavaScript
/// </summary>
/// <returns type="Array" />
/// <param name="elems" type="Array">
/// array The Array to find items in.
/// </param>
/// <param name="fn" type="Function">
/// The function to process each item against.
/// </param>
/// <param name="inv" type="Boolean">
/// Invert the selection - select the opposite of the function.
/// </param>
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 ) {
/// <summary>
/// Translate all items in an array to another array of items.
/// The translation function that is provided to this method is
/// called for each item in the array and is passed one argument:
/// The item to be translated.
/// The function can then return the translated value, 'null'
/// (to remove the item), or an array of values - which will
/// be flattened into the full array.
/// Part of JavaScript
/// </summary>
/// <returns type="Array" />
/// <param name="elems" type="Array">
/// array The Array to translate.
/// </param>
/// <param name="fn" type="Function">
/// The function to process each item against.
/// </param>
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 ) {
/// <summary>
/// Takes a function and returns a new one that will always have a particular scope.
/// </summary>
/// <param name="fn" type="Function">
/// The function whose scope will be changed.
/// </param>
/// <param name="proxy" type="Object">
/// The object to which the scope of the function should be set.
/// </param>
/// <returns type="Function" />
if ( arguments.length === 2 ) {
if ( typeof proxy === "string" ) {
thisObject = fn;
fn = thisObject[ proxy ];
proxy = undefined;
} else if ( proxy && !jQuery.isFunction( proxy ) ) {
thisObject = proxy;
proxy = undefined;
}
}
if ( !proxy && fn ) {
proxy = function() {
return fn.apply( thisObject || this, arguments );
};
}
// Set the guid of unique handler to the same of original handler, so it can be removed
if ( fn ) {
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
}
// So proxy can be declared as an argument
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return (new Date()).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
if ( indexOf ) {
jQuery.inArray = function( elem, array ) {
/// <summary>
/// Determines the index of the first parameter in the array.
/// </summary>
/// <param name="elem">The value to see if it exists in the array.</param>
/// <param name="array" type="Array">The array to look through for the value</param>
/// <returns type="Number" integer="true">The 0-based index of the item if it was found, otherwise -1.</returns>
return indexOf.call( array, elem );
};
}
// Verify that \s matches non-breaking spaces
// (IE fails on this test)
if ( !rwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
// Expose jQuery to the global object
return (window.jQuery = window.$ = jQuery);
})();
// [vsdoc] The following function has been modified for IntelliSense.
// [vsdoc] Stubbing support properties to "false" for IntelliSense compat.
(function() {
jQuery.support = {};
// var root = document.documentElement,
// script = document.createElement("script"),
// div = document.createElement("div"),
// id = "script" + jQuery.now();
// div.style.display = "none";
// div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
// var all = div.getElementsByTagName("*"),
// a = div.getElementsByTagName("a")[0],
// select = document.createElement("select"),
// opt = select.appendChild( document.createElement("option") );
// // Can't get basic test support
// if ( !all || !all.length || !a ) {
// return;
// }
jQuery.support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: false,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: false,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: false,
// Get the style information from getAttribute
// (IE uses .cssText insted)
style: false,
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: false,
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: false,
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: false,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: false,
// 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: false,
// Will be defined later
deleteExpando: false,
optDisabled: false,
checkClone: false,
scriptEval: false,
noCloneEvent: false,
boxModel: false,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableHiddenOffsets: true
};
// // Make sure that the options inside disabled selects aren't marked as disabled
// // (WebKit marks them as diabled)
// select.disabled = true;
// jQuery.support.optDisabled = !opt.disabled;
// script.type = "text/javascript";
// try {
// script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
// } catch(e) {}
// root.insertBefore( script, root.firstChild );
// // Make sure that the execution of code works by injecting a script
// // tag with appendChild/createTextNode
// // (IE doesn't support this, fails, and uses .text instead)
// if ( window[ id ] ) {
// jQuery.support.scriptEval = true;
// delete window[ id ];
// }
// // Test to see if it's possible to delete an expando from an element
// // Fails in Internet Explorer
// try {
// delete script.test;
// } catch(e) {
// jQuery.support.deleteExpando = false;
// }
// root.removeChild( script );
// if ( div.attachEvent && div.fireEvent ) {
// div.attachEvent("onclick", function click() {
// // Cloning a node shouldn't copy over any
// // bound event handlers (IE does this)
// jQuery.support.noCloneEvent = false;
// div.detachEvent("onclick", click);
// });
// div.cloneNode(true).fireEvent("onclick");
// }
// div = document.createElement("div");
// div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";
// var fragment = document.createDocumentFragment();
// fragment.appendChild( div.firstChild );
// // WebKit doesn't clone checked state correctly in fragments
// jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
// // Figure out if the W3C box model works as expected
// // document.body must exist before we can do this
// jQuery(function() {
// var div = document.createElement("div");
// div.style.width = div.style.paddingLeft = "1px";
// document.body.appendChild( div );
// jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
// if ( "zoom" in div.style ) {
// // Check if natively block-level elements act like inline-block
// // elements when setting their display to 'inline' and giving
// // them layout
// // (IE < 8 does this)
// div.style.display = "inline";
// div.style.zoom = 1;
// jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2;
// // Check if elements with layout shrink-wrap their children
// // (IE 6 does this)
// div.style.display = "";
// div.innerHTML = "<div style='width:4px;'></div>";
// jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
// }
// div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";
// var tds = div.getElementsByTagName("td");
// // Check if table cells still have offsetWidth/Height when they are set
// // to display:none and there are still other visible table cells in a
// // table row; if so, offsetWidth/Height are not reliable for use when
// // determining if an element has been hidden directly using
// // display:none (it is still safe to use offsets if a parent element is
// // hidden; don safety goggles and see bug #4512 for more information).
// // (only IE 8 fails this test)
// jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0;
// tds[0].style.display = "";
// tds[1].style.display = "none";
// // Check if empty table cells still have offsetWidth/Height
// // (IE < 8 fail this test)
// jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
// div.innerHTML = "";
// document.body.removeChild( div ).style.display = "none";
// div = tds = null;
// });
// // Technique from Juriy Zaytsev
// // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
// var eventSupported = function( eventName ) {
// var el = document.createElement("div");
// eventName = "on" + eventName;
// var isSupported = (eventName in el);
// if ( !isSupported ) {
// el.setAttribute(eventName, "return;");
// isSupported = typeof el[eventName] === "function";
// }
// el = null;
// return isSupported;
// };
jQuery.support.submitBubbles = false;
jQuery.support.changeBubbles = false;
// // release memory in IE
// root = script = div = all = a = null;
})();
var windowData = {},
rbrace = /^(?:\{.*\}|\[.*\])$/;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
expando: "jQuery" + jQuery.now(),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
data: function( elem, name, data ) {
/// <summary>
/// Store arbitrary data associated with the specified element.
/// </summary>
/// <param name="elem" type="Element">
/// The DOM element to associate with the data.
/// </param>
/// <param name="name" type="String">
/// A string naming the piece of data to set.
/// </param>
/// <param name="value" type="Object">
/// The new data value.
/// </param>
/// <returns type="jQuery" />
if ( !jQuery.acceptData( elem ) ) {
return;
}
elem = elem == window ?
windowData :
elem;
var isNode = elem.nodeType,
id = isNode ? elem[ jQuery.expando ] : null,
cache = jQuery.cache, thisCache;
if ( isNode && !id && typeof name === "string" && data === undefined ) {
return;
}
// Get the data from the object directly
if ( !isNode ) {
cache = elem;
// Compute a unique ID for the element
} else if ( !id ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
}
// Avoid generating a new cache unless none exists and we
// want to manipulate it.
if ( typeof name === "object" ) {
if ( isNode ) {
cache[ id ] = jQuery.extend(cache[ id ], name);
} else {
jQuery.extend( cache, name );
}
} else if ( isNode && !cache[ id ] ) {
cache[ id ] = {};
}
thisCache = isNode ? cache[ id ] : cache;
// Prevent overriding the named cache with undefined values
if ( data !== undefined ) {
thisCache[ name ] = data;
}
return typeof name === "string" ? thisCache[ name ] : thisCache;
},
removeData: function( elem, name ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
elem = elem == window ?
windowData :
elem;
var isNode = elem.nodeType,
id = isNode ? elem[ jQuery.expando ] : elem,
cache = jQuery.cache,
thisCache = isNode ? cache[ id ] : id;
// If we want to remove a specific section of the element's data
if ( name ) {
if ( thisCache ) {
// Remove the section of cache data
delete thisCache[ name ];
// If we've removed all the data, remove the element's cache
if ( isNode && jQuery.isEmptyObject(thisCache) ) {
jQuery.removeData( elem );
}
}
// Otherwise, we want to remove all of the element's data
} else {
if ( isNode && jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
// Completely remove the data cache
} else if ( isNode ) {
delete cache[ id ];
// Remove all fields from the object
} else {
for ( var n in elem ) {
delete elem[ n ];
}
}
}
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
/// <summary>
/// Store arbitrary data associated with the matched elements.
/// </summary>
/// <param name="key" type="String">
/// A string naming the piece of data to set.
/// </param>
/// <param name="value" type="Object">
/// The new data value.
/// </param>
/// <returns type="jQuery" />
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
var attr = this[0].attributes, name;
data = jQuery.data( this[0] );
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = name.substr( 5 );
dataAttr( this[0], name, data[ name ] );
}
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var $this = jQuery( this ),
args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
$this.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
data = elem.getAttribute( "data-" + key );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
!jQuery.isNaN( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
queue: function( elem, type, data ) {
if ( !elem ) {
return;
}
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( !data ) {
return q || [];
}
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
return q;
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift();
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
/// <summary>
/// 1: queue() - Returns a reference to the first element's queue (which is an array of functions).
/// 2: queue(callback) - Adds a new function, to be executed, onto the end of the queue of all matched elements.
/// 3: queue(queue) - Replaces the queue of all matched element with this new queue (the array of functions).
/// </summary>
/// <param name="type" type="Function">The function to add to the queue.</param>
/// <returns type="jQuery" />
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function( i ) {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
/// <summary>
/// Removes a queued function from the front of the queue and executes it.
/// </summary>
/// <param name="type" type="String" optional="true">The type of queue to access.</param>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Set a timer to delay execution of subsequent items in the queue.
/// </summary>
/// <param name="time" type="Number">
/// An integer indicating the number of milliseconds to delay execution of the next item in the queue.
/// </param>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Remove from the queue all items that have not yet been run.
/// </summary>
/// <param name="type" type="String" optional="true">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
return this.queue( type || "fx", [] );
}
});
var rclass = /[\n\t]/g,
rspaces = /\s+/,
rreturn = /\r/g,
rspecialurl = /^(?:href|src|style)$/,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rradiocheck = /^(?:radio|checkbox)$/i;
jQuery.props = {
"for": "htmlFor",
"class": "className",
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
colspan: "colSpan",
tabindex: "tabIndex",
usemap: "useMap",
frameborder: "frameBorder"
};
jQuery.fn.extend({
attr: function( name, value ) {
/// <summary>
/// Set a single property to a computed value, on all matched elements.
/// Instead of a value, a function is provided, that computes the value.
/// Part of DOM/Attributes
/// </summary>
/// <returns type="jQuery" />
/// <param name="name" type="String">
/// The name of the property to set.
/// </param>
/// <param name="value" type="Function">
/// A function returning the value to set.
/// </param>
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name, fn ) {
/// <summary>
/// Remove an attribute from each of the matched elements.
/// Part of DOM/Attributes
/// </summary>
/// <param name="name" type="String">
/// An attribute to remove.
/// </param>
/// <returns type="jQuery" />
return this.each(function(){
jQuery.attr( this, name, "" );
if ( this.nodeType === 1 ) {
this.removeAttribute( name );
}
});
},
addClass: function( value ) {
/// <summary>
/// Adds the specified class(es) to each of the set of matched elements.
/// Part of DOM/Attributes
/// </summary>
/// <param name="value" type="String">
/// One or more class names to be added to the class attribute of each matched element.
/// </param>
/// <returns type="jQuery" />
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.addClass( value.call(this, i, self.attr("class")) );
});
}
if ( value && typeof value === "string" ) {
var classNames = (value || "").split( rspaces );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 ) {
if ( !elem.className ) {
elem.className = value;
} else {
var className = " " + elem.className + " ",
setClass = elem.className;
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
/// <summary>
/// Removes all or the specified class(es) from the set of matched elements.
/// Part of DOM/Attributes
/// </summary>
/// <param name="value" type="String" optional="true">
/// (Optional) A class name to be removed from the class attribute of each matched element.
/// </param>
/// <returns type="jQuery" />
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.removeClass( value.call(this, i, self.attr("class")) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
var classNames = (value || "").split( rspaces );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
var className = (" " + elem.className + " ").replace(rclass, " ");
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[c] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
/// <summary>
/// Add or remove a class from each element in the set of matched elements, depending
/// on either the class's presence or the value of the switch argument.
/// </summary>
/// <param name="value" type="Object">
/// A class name to be toggled for each element in the matched set.
/// </param>
/// <param name="stateVal" type="Object">
/// A boolean value to determine whether the class should be added or removed.
/// </param>
/// <returns type="jQuery" />
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspaces );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery.data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
/// <summary>
/// Checks the current selection against a class and returns whether at least one selection has a given class.
/// </summary>
/// <param name="selector" type="String">The class to check against</param>
/// <returns type="Boolean">True if at least one element in the selection has the class, otherwise false.</returns>
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 ) {
/// <summary>
/// Set the value of every matched element.
/// Part of DOM/Attributes
/// </summary>
/// <returns type="jQuery" />
/// <param name="value" type="String">
/// A string of text or an array of strings to set as the value property of each
/// matched element.
/// </param>
if ( !arguments.length ) {
var elem = this[0];
if ( elem ) {
if ( jQuery.nodeName( elem, "option" ) ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
// We need to handle select boxes special
if ( jQuery.nodeName( elem, "select" ) ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
}
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
// Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction(value);
return this.each(function(i) {
var self = jQuery(this), val = value;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call(this, i, self.val());
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray(val) ) {
val = jQuery.map(val, function (value) {
return value == null ? "" : value + "";
});
}
if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
this.checked = jQuery.inArray( self.val(), val ) >= 0;
} else if ( jQuery.nodeName( this, "select" ) ) {
var values = jQuery.makeArray(val);
jQuery( "option", this ).each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
this.selectedIndex = -1;
}
} else {
this.value = val;
}
});
}
});
jQuery.extend({
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
// don't set attributes on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery(elem)[name](value);
}
var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
// Whether we are setting (or getting)
set = value !== undefined;
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
// These attributes require special treatment
var special = rspecialurl.test( name );
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( name === "selected" && !jQuery.support.optSelected ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
// If applicable, access the attribute via the DOM 0 way
// 'in' checks fail in Blackberry 4.7 #6931
if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
if ( set ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
}
if ( value === null ) {
if ( elem.nodeType === 1 ) {
elem.removeAttribute( name );
}
} else {
elem[ name ] = value;
}
}
// browsers index elements by id/name on forms, give priority to attributes.
if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
return elem.getAttributeNode( name ).nodeValue;
}
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
if ( name === "tabIndex" ) {
var attributeNode = elem.getAttributeNode( "tabIndex" );
return attributeNode && attributeNode.specified ?
attributeNode.value :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
return elem[ name ];
}
if ( !jQuery.support.style && notxml && name === "style" ) {
if ( set ) {
elem.style.cssText = "" + value;
}
return elem.style.cssText;
}
if ( set ) {
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
}
// Ensure that missing attributes return undefined
// Blackberry 4.7 returns "" from getAttribute #6938
if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
return undefined;
}
var attr = !jQuery.support.hrefNormalized && notxml && special ?
// Some attributes require a special call on IE
elem.getAttribute( name, 2 ) :
elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return attr === null ? undefined : attr;
}
});
var rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspace = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
},
focusCounts = { focusin: 0, focusout: 0 };
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) {
elem = window;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery.data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
// Use a key less likely to result in collisions for plain JS objects.
// Fixes bug #7150.
var eventKey = elem.nodeType ? "events" : "__events__",
events = elemData[ eventKey ],
eventHandle = elemData.handle;
if ( typeof events === "function" ) {
// On plain objects events is a fn that holds the the data
// which prevents this data from being JSON serialized
// the function does not need to be called, it just contains the data
eventHandle = events.handle;
events = events.events;
} else if ( !events ) {
if ( !elem.nodeType ) {
// On plain objects, create a fn that acts as the holder
// of the values to avoid JSON serialization of event data
elemData[ eventKey ] = elemData = function(){};
}
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function() {
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for global triggering
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
// don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
eventKey = elem.nodeType ? "events" : "__events__",
elemData = jQuery.data( elem ),
events = elemData && elemData[ eventKey ];
if ( !elemData || !events ) {
return;
}
if ( typeof events === "function" ) {
elemData = events;
events = events.events;
}
// types is actually an event object here
if ( types && types.type ) {
handler = types.handler;
types = types.type;
}
// Unbind all events for the element
if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
types = types || "";
for ( type in events ) {
jQuery.event.remove( elem, type + types );
}
return;
}
// Handle multiple events separated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
types = types.split(" ");
while ( (type = types[ i++ ]) ) {
origType = type;
handleObj = null;
all = type.indexOf(".") < 0;
namespaces = [];
if ( !all ) {
// Namespaced event handlers
namespaces = type.split(".");
type = namespaces.shift();
namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
eventType = events[ type ];
if ( !eventType ) {
continue;
}
if ( !handler ) {
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( all || namespace.test( handleObj.namespace ) ) {
jQuery.event.remove( elem, origType, handleObj.handler, j );
eventType.splice( j--, 1 );
}
}
continue;
}
special = jQuery.event.special[ type ] || {};
for ( j = pos || 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( handler.guid === handleObj.guid ) {
// remove the given handler for the given type
if ( all || namespace.test( handleObj.namespace ) ) {
if ( pos == null ) {
eventType.splice( j--, 1 );
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
if ( pos != null ) {
break;
}
}
}
// remove generic event handler if no more handlers exist
if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
ret = null;
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
var handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
delete elemData.events;
delete elemData.handle;
if ( typeof elemData === "function" ) {
jQuery.removeData( elem, eventKey );
} else if ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem );
}
}
},
// bubbling is internal
trigger: function( event, data, elem /*, bubbling */ ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
// Event object or event type
var type = event.type || event,
bubbling = arguments[3];
if ( !bubbling ) {
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( jQuery.event.global[ type ] ) {
jQuery.each( jQuery.cache, function() {
if ( this.events && this.events[type] ) {
jQuery.event.trigger( event, data, this.handle.elem );
}
});
}
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray( data );
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = elem.nodeType ?
jQuery.data( elem, "handle" ) :
(jQuery.data( elem, "__events__" ) || {}).handle;
if ( handle ) {
handle.apply( elem, data );
}
var parent = elem.parentNode || elem.ownerDocument;
// Trigger an inline bound script
try {
if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
event.result = false;
event.preventDefault();
}
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (inlineError) {}
if ( !event.isPropagationStopped() && parent ) {
jQuery.event.trigger( event, data, parent, true );
} else if ( !event.isDefaultPrevented() ) {
var old,
target = event.target,
targetType = type.replace( rnamespaces, "" ),
isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
special = jQuery.event.special[ targetType ] || {};
if ( (!special._default || special._default.call( elem, event ) === false) &&
!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
try {
if ( target[ targetType ] ) {
// Make sure that we don't accidentally re-trigger the onFOO events
old = target[ "on" + targetType ];
if ( old ) {
target[ "on" + targetType ] = null;
}
jQuery.event.triggered = true;
target[ targetType ]();
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (triggerError) {}
if ( old ) {
target[ "on" + targetType ] = old;
}
jQuery.event.triggered = false;
}
}
},
handle: function( event ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
var all, handlers, namespaces, namespace_re, events,
namespace_sort = [],
args = jQuery.makeArray( arguments );
event = args[0] = jQuery.event.fix( event || window.event );
event.currentTarget = this;
// Namespaced event handlers
all = event.type.indexOf(".") < 0 && !event.exclusive;
if ( !all ) {
namespaces = event.type.split(".");
event.type = namespaces.shift();
namespace_sort = namespaces.slice(0).sort();
namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.namespace = event.namespace || namespace_sort.join(".");
events = jQuery.data(this, this.nodeType ? "events" : "__events__");
if ( typeof events === "function" ) {
events = events.events;
}
handlers = (events || {})[ event.type ];
if ( events && handlers ) {
// Clone the handlers to prevent manipulation
handlers = handlers.slice(0);
for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ];
// Filter the functions by class
if ( all || namespace_re.test( handleObj.namespace ) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
if ( event[ jQuery.expando ] ) {
return event;
}
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target ) {
// Fixes #1925 where srcElement might not be defined either
event.target = event.srcElement || document;
}
// check if target is a textnode (safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement,
body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
},
// Deprecated, use jQuery.guid instead
guid: 1E8,
// Deprecated, use jQuery.proxy instead
proxy: jQuery.proxy,
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady,
teardown: jQuery.noop
},
live: {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Event type
} else {
this.type = src;
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try {
// Traverse up the tree
while ( parent && parent !== this ) {
parent = parent.parentNode;
}
if ( parent !== this ) {
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
// assuming we've left the element since we most likely mousedover a xul element
} catch(e) { }
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
e.liveFired = undefined;
return trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
e.liveFired = undefined;
return trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
var changeFilters,
getVal = function( elem ) {
var type = elem.type, val = elem.value;
if ( type === "radio" || type === "checkbox" ) {
val = elem.checked;
} else if ( type === "select-multiple" ) {
val = elem.selectedIndex > -1 ?
jQuery.map( elem.options, function( elem ) {
return elem.selected;
}).join("-") :
"";
} else if ( elem.nodeName.toLowerCase() === "select" ) {
val = elem.selectedIndex;
}
return val;
},
testChange = function testChange( e ) {
var elem = e.target, data, val;
if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
return;
}
data = jQuery.data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
jQuery.data( elem, "_change_data", val );
}
if ( data === undefined || val === data ) {
return;
}
if ( data != null || val ) {
e.type = "change";
e.liveFired = undefined;
return jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
beforedeactivate: testChange,
click: function( e ) {
var elem = e.target, type = elem.type;
if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
return testChange.call( this, e );
}
},
// Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) {
var elem = e.target, type = elem.type;
if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
return testChange.call( this, e );
}
},
// Beforeactivate happens also before the previous element is blurred
// with this event you can't trigger a change event, but you can store
// information
beforeactivate: function( e ) {
var elem = e.target;
jQuery.data( elem, "_change_data", getVal(elem) );
}
},
setup: function( data, namespaces ) {
if ( this.type === "file" ) {
return false;
}
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
}
return rformElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return rformElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters;
// Handle when the input is .focus()'d
changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) {
args[0].type = type;
return jQuery.event.handle.apply( elem, args );
}
// Create "bubbling" focus and blur events
if ( document.addEventListener ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
jQuery.event.special[ fix ] = {
setup: function() {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
if ( focusCounts[fix]++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
if ( --focusCounts[fix] === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
function handler( e ) {
e = jQuery.event.fix( e );
e.type = fix;
return jQuery.event.trigger( e, null, e.target );
}
});
}
// jQuery.each(["bind", "one"], function( i, name ) {
// jQuery.fn[ name ] = function( type, data, fn ) {
// // Handle object literals
// if ( typeof type === "object" ) {
// for ( var key in type ) {
// this[ name ](key, data, type[key], fn);
// }
// return this;
// }
// if ( jQuery.isFunction( data ) || data === false ) {
// fn = data;
// data = undefined;
// }
// var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
// jQuery( this ).unbind( event, handler );
// return fn.apply( this, arguments );
// }) : fn;
// if ( type === "unload" && name !== "one" ) {
// this.one( type, data, fn );
// } else {
// for ( var i = 0, l = this.length; i < l; i++ ) {
// jQuery.event.add( this[i], type, handler, data );
// }
// }
// return this;
// };
// });
jQuery.fn[ "bind" ] = function( type, data, fn ) {
/// <summary>
/// Binds a handler to one or more events for each matched element. Can also bind custom events.
/// </summary>
/// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param>
/// <param name="data" optional="true" type="Object">Additional data passed to the event handler as event.data</param>
/// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param>
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ "bind" ](key, data, type[key], fn);
}
return this;
}
if ( jQuery.isFunction( data ) ) {
fn = data;
data = undefined;
}
var handler = "bind" === "one" ? jQuery.proxy( fn, function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
}) : fn;
return type === "unload" && "bind" !== "one" ?
this.one( type, data, fn ) :
this.each(function() {
jQuery.event.add( this, type, handler, data );
});
};
jQuery.fn[ "one" ] = function( type, data, fn ) {
/// <summary>
/// Binds a handler to one or more events to be executed exactly once for each matched element.
/// </summary>
/// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param>
/// <param name="data" optional="true" type="Object">Additional data passed to the event handler as event.data</param>
/// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param>
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ "one" ](key, data, type[key], fn);
}
return this;
}
if ( jQuery.isFunction( data ) ) {
fn = data;
data = undefined;
}
var handler = "one" === "one" ? jQuery.proxy( fn, function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
}) : fn;
return type === "unload" && "one" !== "one" ?
this.one( type, data, fn ) :
this.each(function() {
jQuery.event.add( this, type, handler, data );
});
};
jQuery.fn.extend({
unbind: function( type, fn ) {
/// <summary>
/// Unbinds a handler from one or more events for each matched element.
/// </summary>
/// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param>
/// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param>
// 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 ) {
/// <summary>
/// Triggers a type of event on every matched element.
/// </summary>
/// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param>
/// <param name="data" optional="true" type="Array">Additional data passed to the event handler as additional arguments.</param>
/// <param name="fn" type="Function">This parameter is undocumented.</param>
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
/// <summary>
/// Triggers all bound event handlers on an element for a specific event type without executing the browser's default actions.
/// </summary>
/// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param>
/// <param name="data" optional="true" type="Array">Additional data passed to the event handler as additional arguments.</param>
/// <param name="fn" type="Function">This parameter is undocumented.</param>
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 ) {
/// <summary>
/// Toggles among two or more function calls every other click.
/// </summary>
/// <param name="fn" type="Function">The functions among which to toggle execution</param>
// 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 ) {
/// <summary>
/// Simulates hovering (moving the mouse on or off of an object).
/// </summary>
/// <param name="fnOver" type="Function">The function to fire when the mouse is moved over a matched element.</param>
/// <param name="fnOut" type="Function">The function to fire when the mouse is moved off of a matched element.</param>
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
var liveMap = {
focus: "focusin",
blur: "focusout",
mouseenter: "mouseover",
mouseleave: "mouseout"
};
// jQuery.each(["live", "die"], function( i, name ) {
// jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
// var type, i = 0, match, namespaces, preType,
// selector = origSelector || this.selector,
// context = origSelector ? this : jQuery( this.context );
// if ( typeof types === "object" && !types.preventDefault ) {
// for ( var key in types ) {
// context[ name ]( key, data, types[key], selector );
// }
// return this;
// }
// if ( jQuery.isFunction( data ) ) {
// fn = data;
// data = undefined;
// }
// types = (types || "").split(" ");
// while ( (type = types[ i++ ]) != null ) {
// match = rnamespaces.exec( type );
// namespaces = "";
// if ( match ) {
// namespaces = match[0];
// type = type.replace( rnamespaces, "" );
// }
// if ( type === "hover" ) {
// types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
// continue;
// }
// preType = type;
// if ( type === "focus" || type === "blur" ) {
// types.push( liveMap[ type ] + namespaces );
// type = type + namespaces;
// } else {
// type = (liveMap[ type ] || type) + namespaces;
// }
// if ( name === "live" ) {
// // bind live handler
// for ( var j = 0, l = context.length; j < l; j++ ) {
// jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
// { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
// }
// } else {
// // unbind live handler
// context.unbind( "live." + liveConvert( type, selector ), fn );
// }
// }
// return this;
// };
// });
jQuery.fn[ "live" ] = function( types, data, fn ) {
/// <summary>
/// Attach a handler to the event for all elements which match the current selector, now or
/// in the future.
/// </summary>
/// <param name="types" type="String">
/// A string containing a JavaScript event type, such as "click" or "keydown".
/// </param>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute at the time the event is triggered.
/// </param>
/// <returns type="jQuery" />
var type, i = 0;
if ( jQuery.isFunction( data ) ) {
fn = data;
data = undefined;
}
types = (types || "").split( /\s+/ );
while ( (type = types[ i++ ]) != null ) {
type = type === "focus" ? "focusin" : // focus --> focusin
type === "blur" ? "focusout" : // blur --> focusout
type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support
type;
if ( "live" === "live" ) {
// bind live handler
jQuery( this.context ).bind( liveConvert( type, this.selector ), {
data: data, selector: this.selector, live: type
}, fn );
} else {
// unbind live handler
jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null );
}
}
return this;
}
jQuery.fn[ "die" ] = function( types, data, fn ) {
/// <summary>
/// Remove all event handlers previously attached using .live() from the elements.
/// </summary>
/// <param name="types" type="String">
/// A string containing a JavaScript event type, such as click or keydown.
/// </param>
/// <param name="data" type="Object">
/// The function that is to be no longer executed.
/// </param>
/// <returns type="jQuery" />
var type, i = 0;
if ( jQuery.isFunction( data ) ) {
fn = data;
data = undefined;
}
types = (types || "").split( /\s+/ );
while ( (type = types[ i++ ]) != null ) {
type = type === "focus" ? "focusin" : // focus --> focusin
type === "blur" ? "focusout" : // blur --> focusout
type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support
type;
if ( "die" === "live" ) {
// bind live handler
jQuery( this.context ).bind( liveConvert( type, this.selector ), {
data: data, selector: this.selector, live: type
}, fn );
} else {
// unbind live handler
jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null );
}
}
return this;
}
function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
events = jQuery.data( this, this.nodeType ? "events" : "__events__" );
if ( typeof events === "function" ) {
events = events.events;
}
// Make sure we avoid non-left-click bubbling in Firefox (#3861)
if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) {
return;
}
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.liveFired = this;
var live = events.live.slice(0);
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
selectors.push( handleObj.selector );
} else {
live.splice( j--, 1 );
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
close = match[i];
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) ) {
elem = close.elem;
related = null;
// Those two events require additional checking
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj, level: close.level });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
if ( maxLevel && match.level > maxLevel ) {
break;
}
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
ret = match.handleObj.origHandler.apply( match.elem, arguments );
if ( ret === false || event.isPropagationStopped() ) {
maxLevel = match.level;
if ( ret === false ) {
stop = false;
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return stop;
}
function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&");
}
// jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
// "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
// "change select submit keydown keypress keyup error").split(" "), function( i, name ) {
// // Handle event binding
// jQuery.fn[ name ] = function( data, fn ) {
// if ( fn == null ) {
// fn = data;
// data = null;
// }
// return arguments.length > 0 ?
// this.bind( name, data, fn ) :
// this.trigger( name );
// };
// if ( jQuery.attrFn ) {
// jQuery.attrFn[ name ] = true;
// }
// });
jQuery.fn[ "blur" ] = function( fn ) {
/// <summary>
/// 1: blur() - Triggers the blur event of each matched element.
/// 2: blur(fn) - Binds a function to the blur event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "blur", fn ) : this.trigger( "blur" );
};
jQuery.fn[ "focus" ] = function( fn ) {
/// <summary>
/// 1: focus() - Triggers the focus event of each matched element.
/// 2: focus(fn) - Binds a function to the focus event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "focus", fn ) : this.trigger( "focus" );
};
jQuery.fn[ "focusin" ] = function( fn ) {
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event.
/// </summary>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return fn ? this.bind( "focusin", fn ) : this.trigger( "focusin" );
};
jQuery.fn[ "focusout" ] = function( fn ) {
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return fn ? this.bind( "focusout", fn ) : this.trigger( "focusout" );
};
jQuery.fn[ "load" ] = function( fn ) {
/// <summary>
/// 1: load() - Triggers the load event of each matched element.
/// 2: load(fn) - Binds a function to the load event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "load", fn ) : this.trigger( "load" );
};
jQuery.fn[ "resize" ] = function( fn ) {
/// <summary>
/// 1: resize() - Triggers the resize event of each matched element.
/// 2: resize(fn) - Binds a function to the resize event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "resize", fn ) : this.trigger( "resize" );
};
jQuery.fn[ "scroll" ] = function( fn ) {
/// <summary>
/// 1: scroll() - Triggers the scroll event of each matched element.
/// 2: scroll(fn) - Binds a function to the scroll event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "scroll", fn ) : this.trigger( "scroll" );
};
jQuery.fn[ "unload" ] = function( fn ) {
/// <summary>
/// 1: unload() - Triggers the unload event of each matched element.
/// 2: unload(fn) - Binds a function to the unload event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "unload", fn ) : this.trigger( "unload" );
};
jQuery.fn[ "click" ] = function( fn ) {
/// <summary>
/// 1: click() - Triggers the click event of each matched element.
/// 2: click(fn) - Binds a function to the click event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "click", fn ) : this.trigger( "click" );
};
jQuery.fn[ "dblclick" ] = function( fn ) {
/// <summary>
/// 1: dblclick() - Triggers the dblclick event of each matched element.
/// 2: dblclick(fn) - Binds a function to the dblclick event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "dblclick", fn ) : this.trigger( "dblclick" );
};
jQuery.fn[ "mousedown" ] = function( fn ) {
/// <summary>
/// Binds a function to the mousedown event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "mousedown", fn ) : this.trigger( "mousedown" );
};
jQuery.fn[ "mouseup" ] = function( fn ) {
/// <summary>
/// Bind a function to the mouseup event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "mouseup", fn ) : this.trigger( "mouseup" );
};
jQuery.fn[ "mousemove" ] = function( fn ) {
/// <summary>
/// Bind a function to the mousemove event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "mousemove", fn ) : this.trigger( "mousemove" );
};
jQuery.fn[ "mouseover" ] = function( fn ) {
/// <summary>
/// Bind a function to the mouseover event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "mouseover", fn ) : this.trigger( "mouseover" );
};
jQuery.fn[ "mouseout" ] = function( fn ) {
/// <summary>
/// Bind a function to the mouseout event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "mouseout", fn ) : this.trigger( "mouseout" );
};
jQuery.fn[ "mouseenter" ] = function( fn ) {
/// <summary>
/// Bind a function to the mouseenter event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "mouseenter", fn ) : this.trigger( "mouseenter" );
};
jQuery.fn[ "mouseleave" ] = function( fn ) {
/// <summary>
/// Bind a function to the mouseleave event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "mouseleave", fn ) : this.trigger( "mouseleave" );
};
jQuery.fn[ "change" ] = function( fn ) {
/// <summary>
/// 1: change() - Triggers the change event of each matched element.
/// 2: change(fn) - Binds a function to the change event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "change", fn ) : this.trigger( "change" );
};
jQuery.fn[ "select" ] = function( fn ) {
/// <summary>
/// 1: select() - Triggers the select event of each matched element.
/// 2: select(fn) - Binds a function to the select event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "select", fn ) : this.trigger( "select" );
};
jQuery.fn[ "submit" ] = function( fn ) {
/// <summary>
/// 1: submit() - Triggers the submit event of each matched element.
/// 2: submit(fn) - Binds a function to the submit event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "submit", fn ) : this.trigger( "submit" );
};
jQuery.fn[ "keydown" ] = function( fn ) {
/// <summary>
/// 1: keydown() - Triggers the keydown event of each matched element.
/// 2: keydown(fn) - Binds a function to the keydown event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "keydown", fn ) : this.trigger( "keydown" );
};
jQuery.fn[ "keypress" ] = function( fn ) {
/// <summary>
/// 1: keypress() - Triggers the keypress event of each matched element.
/// 2: keypress(fn) - Binds a function to the keypress event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "keypress", fn ) : this.trigger( "keypress" );
};
jQuery.fn[ "keyup" ] = function( fn ) {
/// <summary>
/// 1: keyup() - Triggers the keyup event of each matched element.
/// 2: keyup(fn) - Binds a function to the keyup event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "keyup", fn ) : this.trigger( "keyup" );
};
jQuery.fn[ "error" ] = function( fn ) {
/// <summary>
/// 1: error() - Triggers the error event of each matched element.
/// 2: error(fn) - Binds a function to the error event of each matched element.
/// </summary>
/// <param name="fn" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return fn ? this.bind( "error", fn ) : this.trigger( "error" );
};
// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
jQuery(window).bind("unload", function() {
for ( var id in jQuery.cache ) {
if ( jQuery.cache[ id ].handle ) {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
} catch(e) {}
}
}
});
}
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
/// <summary>
/// Removes all duplicate elements from an array of elements.
/// </summary>
/// <param name="array" type="Array<Element>">The array to translate</param>
/// <returns type="Array<Element>">The array after translation.</returns>
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var match,
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName( "*" );
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var found, item,
filter = Expr.filter[ type ],
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !/\W/.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
return context.getElementsByTagName( match[1] );
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace(/\\/g, "");
},
TAG: function( match, curLoop ) {
return match[1].toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
/// <summary>
/// Internal use only; use hasClass('class')
/// </summary>
/// <private />
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
return "text" === elem.type;
},
radio: function( elem ) {
return "radio" === elem.type;
},
checkbox: function( elem ) {
return "checkbox" === elem.type;
},
file: function( elem ) {
return "file" === elem.type;
},
password: function( elem ) {
return "password" === elem.type;
},
submit: function( elem ) {
return "submit" === elem.type;
},
image: function( elem ) {
return "image" === elem.type;
},
reset: function( elem ) {
return "reset" === elem.type;
},
button: function( elem ) {
return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( "Syntax error, unrecognized expression: " + name );
}
},
CHILD: function( elem, match ) {
var type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
var first = match[2],
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// If the nodes are siblings (or identical) we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// [vsdoc] The following function has been modified for IntelliSense.
// 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;
})();
// [vsdoc] The following function has been modified for IntelliSense.
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
// var div = document.createElement("div");
// div.appendChild( document.createComment("") );
// Make sure no comments are found
// if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
// }
// Check to see if an attribute returns normalized href attributes
// div.innerHTML = "<a href='#'></a>";
// if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
// div.firstChild.getAttribute("href") !== "#" ) {
// Expr.attrHandle.href = function( elem ) {
// return elem.getAttribute( "href", 2 );
// };
// }
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Make sure that attribute selectors are quoted
query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
if ( context.nodeType === 9 ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var old = context.getAttribute( "id" ),
nid = old || id;
if ( !old ) {
context.setAttribute( "id", nid );
}
try {
return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra );
} catch(pseudoError) {
} finally {
if ( !old ) {
context.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector,
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
if ( matches ) {
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
return matches.call( node, expr );
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
/// <summary>
/// Check to see if a DOM node is within another DOM node.
/// </summary>
/// <param name="a" type="Object">
/// The DOM element that may contain the other element.
/// </param>
/// <param name="b" type="Object">
/// The DOM node that may be contained by the other element.
/// </param>
/// <returns type="Boolean" />
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
/// <summary>
/// Check to see if a DOM node is within another DOM node.
/// </summary>
/// <param name="a" type="Object">
/// The DOM element that may contain the other element.
/// </param>
/// <param name="b" type="Object">
/// The DOM node that may be contained by the other element.
/// </param>
/// <returns type="Boolean" />
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
/// <summary>
/// Determines if the parameter passed is an XML document.
/// </summary>
/// <param name="elem" type="Object">The object to test</param>
/// <returns type="Boolean">True if the parameter is an XML document; otherwise false.</returns>
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS;
jQuery.fn.extend({
find: function( selector ) {
/// <summary>
/// Searches for all elements that match the specified expression.
/// This method is a good way to find additional descendant
/// elements with which to process.
/// All searching is done using a jQuery expression. The expression can be
/// written using CSS 1-3 Selector syntax, or basic XPath.
/// Part of DOM/Traversing
/// </summary>
/// <returns type="jQuery" />
/// <param name="selector" type="String">
/// An expression to search with.
/// </param>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Reduce the set of matched elements to those that have a descendant that matches the
/// selector or DOM element.
/// </summary>
/// <param name="target" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Removes any elements inside the array of elements from the set
/// of matched elements. This method is used to remove one or more
/// elements from a jQuery object.
/// Part of DOM/Traversing
/// </summary>
/// <param name="selector" type="jQuery">
/// A set of elements to remove from the jQuery set of matched elements.
/// </param>
/// <returns type="jQuery" />
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
/// <summary>
/// Removes all elements from the set of matched elements that do not
/// pass the specified filter. This method is used to narrow down
/// the results of a search.
/// })
/// Part of DOM/Traversing
/// </summary>
/// <returns type="jQuery" />
/// <param name="selector" type="Function">
/// A function to use for filtering
/// </param>
/// <returns type="jQuery" />
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
/// <summary>
/// Checks the current selection against an expression and returns true,
/// if at least one element of the selection fits the given expression.
/// Does return false, if no element fits or the expression is not valid.
/// filter(String) is used internally, therefore all rules that apply there
/// apply here, too.
/// Part of DOM/Traversing
/// </summary>
/// <returns type="Boolean" />
/// <param name="expr" type="String">
/// The expression with which to filter
/// </param>
return !!selector && jQuery.filter( selector, this ).length > 0;
},
closest: function( selectors, context ) {
/// <summary>
/// Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
/// </summary>
/// <param name="selectors" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <param name="context" type="Element">
/// A DOM element within which a matching element may be found. If no context is passed
/// in then the context of the jQuery set will be used instead.
/// </param>
/// <returns type="jQuery" />
var ret = [], i, l, cur = this[0];
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];
if ( !matches[selector] ) {
matches[selector] = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}
while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[selector];
if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
}
return ret;
}
var pos = POS.test( selectors ) ?
jQuery( selectors, context || this.context ) : null;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique(ret) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
/// <summary>
/// Searches every matched element for the object and returns
/// the index of the element, if found, starting with zero.
/// Returns -1 if the object wasn't found.
/// Part of Core
/// </summary>
/// <returns type="Number" />
/// <param name="elem" type="Element">
/// Object to search for
/// </param>
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 ) {
/// <summary>
/// Adds one or more Elements to the set of matched elements.
/// Part of DOM/Traversing
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match additional elements against.
/// </param>
/// <param name="context" type="Element">
/// Add some elements rooted against the specified context.
/// </param>
/// <returns type="jQuery" />
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() {
/// <summary>
/// Adds the previous selection to the current selection.
/// </summary>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Get the ancestors of each element in the current set of matched elements, up to but not
/// including the element matched by the selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching ancestor
/// elements.
/// </param>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Get all following siblings of each element up to but not including the element matched
/// by the selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching following
/// sibling elements.
/// </param>
/// <returns type="jQuery" />
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
/// <summary>
/// Get all preceding siblings of each element up to but not including the element matched
/// by the selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching preceding
/// sibling elements.
/// </param>
/// <returns type="jQuery" />
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call(arguments).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
/// <summary>
/// This member is internal only.
/// </summary>
/// <private />
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 ) {
/// <summary>
/// This member is internal only.
/// </summary>
/// <private />
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
/// <summary>
/// This member is internal only.
/// </summary>
/// <private />
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return (elem === qualifier) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
});
}
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked (html5)
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
raction = /\=([^="'>\s]+\/)>/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
/// <summary>
/// Set the text contents of all matched elements.
/// Similar to html(), but escapes HTML (replace "<" and ">" with their
/// HTML entities).
/// Part of DOM/Attributes
/// </summary>
/// <returns type="jQuery" />
/// <param name="text" type="String">
/// The text value to set the contents of the element to.
/// </param>
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 ) {
/// <summary>
/// Wrap all matched elements with a structure of other elements.
/// This wrapping process is most useful for injecting additional
/// stucture into a document, without ruining the original semantic
/// qualities of a document.
/// This works by going through the first element
/// provided and finding the deepest ancestor element within its
/// structure - it is that element that will en-wrap everything else.
/// This does not work with elements that contain text. Any necessary text
/// must be added after the wrapping is done.
/// Part of DOM/Manipulation
/// </summary>
/// <returns type="jQuery" />
/// <param name="html" type="Element">
/// A DOM element that will be wrapped around the target.
/// </param>
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 ) {
/// <summary>
/// Wraps the inner child contents of each matched elemenht (including text nodes) with an HTML structure.
/// </summary>
/// <param name="html" type="String">
/// A string of HTML or a DOM element that will be wrapped around the target contents.
/// </param>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Wrap all matched elements with a structure of other elements.
/// This wrapping process is most useful for injecting additional
/// stucture into a document, without ruining the original semantic
/// qualities of a document.
/// This works by going through the first element
/// provided and finding the deepest ancestor element within its
/// structure - it is that element that will en-wrap everything else.
/// This does not work with elements that contain text. Any necessary text
/// must be added after the wrapping is done.
/// Part of DOM/Manipulation
/// </summary>
/// <returns type="jQuery" />
/// <param name="html" type="Element">
/// A DOM element that will be wrapped around the target.
/// </param>
return this.each(function() {
jQuery( this ).wrapAll( html );
});
},
unwrap: function() {
/// <summary>
/// Remove the parents of the set of matched elements from the DOM, leaving the matched
/// elements in their place.
/// </summary>
/// <returns type="jQuery" />
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
/// <summary>
/// Append content to the inside of every matched element.
/// This operation is similar to doing an appendChild to all the
/// specified elements, adding them into the document.
/// Part of DOM/Manipulation
/// </summary>
/// <returns type="jQuery" />
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
/// <summary>
/// Prepend content to the inside of every matched element.
/// This operation is the best way to insert elements
/// inside, at the beginning, of all matched elements.
/// Part of DOM/Manipulation
/// </summary>
/// <returns type="jQuery" />
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
/// <summary>
/// Insert content before each of the matched elements.
/// Part of DOM/Manipulation
/// </summary>
/// <returns type="jQuery" />
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() {
/// <summary>
/// Insert content after each of the matched elements.
/// Part of DOM/Manipulation
/// </summary>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Clone matched DOM Elements and select the clones.
/// This is useful for moving copies of the elements to another
/// location in the DOM.
/// Part of DOM/Manipulation
/// </summary>
/// <returns type="jQuery" />
/// <param name="deep" type="Boolean" optional="true">
/// (Optional) Set to false if you don't want to clone all descendant nodes, in addition to the element itself.
/// </param>
// Do the clone
var ret = this.map(function() {
if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
// IE copies events bound via attachEvent when
// using cloneNode. Calling detachEvent on the
// clone will also remove the events from the orignal
// In order to get around this, we use innerHTML.
// Unfortunately, this means some modifications to
// attributes in IE that are actually only stored
// as properties will not be copied (such as the
// the name attribute on an input).
var html = this.outerHTML,
ownerDocument = this.ownerDocument;
if ( !html ) {
var div = ownerDocument.createElement("div");
div.appendChild( this.cloneNode(true) );
html = div.innerHTML;
}
return jQuery.clean([html.replace(rinlinejQuery, "")
// Handle the case in IE 8 where action=/test/> self-closes a tag
.replace(raction, '="$1">')
.replace(rleadingWhitespace, "")], ownerDocument)[0];
} else {
return this.cloneNode(true);
}
});
// Copy the events from the original to the clone
if ( events === true ) {
cloneCopyEvent( this, ret );
cloneCopyEvent( this.find("*"), ret.find("*") );
}
// Return the cloned set
return ret;
},
html: function( value ) {
/// <summary>
/// Set the html contents of every matched element.
/// This property is not available on XML documents.
/// Part of DOM/Attributes
/// </summary>
/// <returns type="jQuery" />
/// <param name="value" type="String">
/// A string of HTML to set as the content of each matched element.
/// </param>
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
/// <summary>
/// Replaces all matched element with the specified HTML or DOM elements.
/// </summary>
/// <param name="value" type="Object">
/// The content to insert. May be an HTML string, DOM element, or jQuery object.
/// </param>
/// <returns type="jQuery">The element that was just replaced.</returns>
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 ) {
/// <summary>
/// Remove the set of matched elements from the DOM.
/// </summary>
/// <param name="selector" type="String">
/// A selector expression that filters the set of matched elements to be removed.
/// </param>
/// <returns type="jQuery" />
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
/// <param name="args" type="Array">
/// Args
/// </param>
/// <param name="table" type="Boolean">
/// Insert TBODY in TABLEs if one is not found.
/// </param>
/// <param name="dir" type="Number">
/// If dir<0, process args in reverse order.
/// </param>
/// <param name="fn" type="Function">
/// The function doing the DOM manipulation.
/// </param>
/// <returns type="jQuery" />
/// <summary>
/// Part of Core
/// </summary>
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
i > 0 || results.cacheable || this.length > 1 ?
fragment.cloneNode(true) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent(orig, ret) {
var i = 0;
ret.each(function() {
if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
return;
}
var oldData = jQuery.data( orig[i++] ),
curData = jQuery.data( this, oldData ),
events = oldData && oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var handler in events[ type ] ) {
jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
}
}
}
});
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
!rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults ) {
if ( cacheresults !== 1 ) {
fragment = cacheresults;
}
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
// jQuery.each({
// appendTo: "append",
// prependTo: "prepend",
// insertBefore: "before",
// insertAfter: "after",
// replaceAll: "replaceWith"
// }, function( name, original ) {
// jQuery.fn[ name ] = function( selector ) {
// var ret = [],
// insert = jQuery( selector ),
// parent = this.length === 1 && this[0].parentNode;
// if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
// insert[ original ]( this[0] );
// return this;
// } else {
// for ( var i = 0, l = insert.length; i < l; i++ ) {
// var elems = (i > 0 ? this.clone(true) : this).get();
// jQuery( insert[i] )[ original ]( elems );
// ret = ret.concat( elems );
// }
//
// return this.pushStack( ret, name, insert.selector );
// }
// };
// });
jQuery.fn[ "appendTo" ] = function( selector ) {
/// <summary>
/// Append all of the matched elements to another, specified, set of elements.
/// As of jQuery 1.3.2, returns all of the inserted elements.
/// This operation is, essentially, the reverse of doing a regular
/// $(A).append(B), in that instead of appending B to A, you're appending
/// A to B.
/// </summary>
/// <param name="selector" type="Selector">
/// target to which the content will be appended.
/// </param>
/// <returns type="jQuery" />
var ret = [], insert = jQuery( selector );
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ "append" ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, "appendTo", insert.selector );
};
jQuery.fn[ "prependTo" ] = function( selector ) {
/// <summary>
/// Prepend all of the matched elements to another, specified, set of elements.
/// As of jQuery 1.3.2, returns all of the inserted elements.
/// This operation is, essentially, the reverse of doing a regular
/// $(A).prepend(B), in that instead of prepending B to A, you're prepending
/// A to B.
/// </summary>
/// <param name="selector" type="Selector">
/// target to which the content will be appended.
/// </param>
/// <returns type="jQuery" />
var ret = [], insert = jQuery( selector );
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ "prepend" ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, "prependTo", insert.selector );
};
jQuery.fn[ "insertBefore" ] = function( selector ) {
/// <summary>
/// Insert all of the matched elements before another, specified, set of elements.
/// As of jQuery 1.3.2, returns all of the inserted elements.
/// This operation is, essentially, the reverse of doing a regular
/// $(A).before(B), in that instead of inserting B before A, you're inserting
/// A before B.
/// </summary>
/// <param name="content" type="String">
/// Content after which the selected element(s) is inserted.
/// </param>
/// <returns type="jQuery" />
var ret = [], insert = jQuery( selector );
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ "before" ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, "insertBefore", insert.selector );
};
jQuery.fn[ "insertAfter" ] = function( selector ) {
/// <summary>
/// Insert all of the matched elements after another, specified, set of elements.
/// As of jQuery 1.3.2, returns all of the inserted elements.
/// This operation is, essentially, the reverse of doing a regular
/// $(A).after(B), in that instead of inserting B after A, you're inserting
/// A after B.
/// </summary>
/// <param name="content" type="String">
/// Content after which the selected element(s) is inserted.
/// </param>
/// <returns type="jQuery" />
var ret = [], insert = jQuery( selector );
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ "after" ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, "insertAfter", insert.selector );
};
jQuery.fn[ "replaceAll" ] = function( selector ) {
/// <summary>
/// Replaces the elements matched by the specified selector with the matched elements.
/// As of jQuery 1.3.2, returns all of the inserted elements.
/// </summary>
/// <param name="selector" type="Selector">The elements to find and replace the matched elements with.</param>
/// <returns type="jQuery" />
var ret = [], insert = jQuery( selector );
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ "replaceWith" ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, "replaceAll", insert.selector );
};
jQuery.each({
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
if ( !keepData && this.nodeType === 1 ) {
jQuery.cleanData( this.getElementsByTagName("*") );
jQuery.cleanData( [ this ] );
}
if ( this.parentNode ) {
this.parentNode.removeChild( this );
}
}
},
empty: function() {
/// <summary>
/// Removes all child nodes from the set of matched elements.
/// Part of DOM/Manipulation
/// </summary>
/// <returns type="jQuery" />
// Remove element nodes and prevent memory leaks
if ( this.nodeType === 1 ) {
jQuery.cleanData( this.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( this.firstChild ) {
this.removeChild( this.firstChild );
}
}
}, function( name, fn ) {
jQuery.fn[ name ] = function() {
return this.each( fn, arguments );
};
});
jQuery.extend({
clean: function( elems, context, fragment, scripts ) {
/// <summary>
/// This method is internal only.
/// </summary>
/// <private />
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [];
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" && !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( var j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id, cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rdashAlpha = /-([a-z])/ig,
rupper = /([A-Z])/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle,
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn.css = function( name, value ) {
/// <summary>
/// Set a single style property to a value, on all matched elements.
/// If a number is provided, it is automatically converted into a pixel value.
/// Part of CSS
/// </summary>
/// <returns type="jQuery" />
/// <param name="name" type="String">
/// A CSS property name.
/// </param>
/// <param name="value" type="String">
/// A value to set for the property.
/// </param>
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"zIndex": true,
"fontWeight": true,
"opacity": true,
"zoom": true,
"lineHeight": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
// Make sure that NaN and null values aren't set. See: #7116
if ( typeof value === "number" && isNaN( value ) || value == null ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
/// <summary>
/// This method is internal only.
/// </summary>
/// <private />
// Make sure that we're working with the right name
var ret, origName = jQuery.camelCase( name ),
hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name, origName );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
/// <summary>
/// Swap in/out style options.
/// </summary>
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
},
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
val = getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
if ( val <= 0 ) {
val = curCSS( elem, name, name );
if ( val === "0px" && currentStyle ) {
val = currentStyle( elem, name, name );
}
if ( val != null ) {
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
}
if ( val < 0 || val == null ) {
val = elem.style[ name ];
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
return typeof val === "string" ? val : val + "px";
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat(value);
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
(parseFloat(RegExp.$1) / 100) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style;
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// Set the alpha filter to set the opacity
var opacity = jQuery.isNaN(value) ?
"" :
"alpha(opacity=" + value * 100 + ")",
filter = style.filter || "";
style.filter = ralpha.test(filter) ?
filter.replace(ralpha, opacity) :
style.filter + ' ' + opacity;
}
};
}
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, newName, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( !(defaultView = elem.ownerDocument.defaultView) ) {
return undefined;
}
if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
elem.runtimeStyle.left = elem.currentStyle.left;
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
elem.runtimeStyle.left = rsLeft;
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
var which = name === "width" ? cssWidth : cssHeight,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" ) {
return val;
}
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
}
if ( extra === "margin" ) {
val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;
} else {
val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
}
});
return val;
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var jsc = jQuery.now(),
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rnoContent = /^(?:GET|HEAD)$/,
rbracket = /\[\]$/,
jsre = /\=\?(&|$)/,
rquery = /\?/,
rts = /([?&])_=[^&]*/,
rurl = /^(\w+:)?\/\/([^\/?#]+)/,
r20 = /%20/g,
rhash = /#.*$/,
// Keep a copy of the old load method
_load = jQuery.fn.load;
jQuery.fn.extend({
load: function( url, params, callback ) {
/// <summary>
/// Loads HTML from a remote file and injects it into the DOM. By default performs a GET request, but if parameters are included
/// then a POST will be performed.
/// </summary>
/// <param name="url" type="String">The URL of the HTML page to load.</param>
/// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param>
/// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus, XMLHttpRequest) such that this maps the injected DOM element.</param>
/// <returns type="jQuery" />
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf(" ");
if ( off >= 0 ) {
var selector = url.slice(off, url.length);
url = url.slice(0, off);
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function( res, status ) {
// If successful, inject the HTML into all the matched elements
if ( status === "success" || status === "notmodified" ) {
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
}
if ( callback ) {
self.each( callback, [res.responseText, status, res] );
}
}
});
return this;
},
serialize: function() {
/// <summary>
/// Serializes a set of input elements into a string of data.
/// </summary>
/// <returns type="String">The serialized result</returns>
return jQuery.param(this.serializeArray());
},
serializeArray: function() {
/// <summary>
/// Serializes all forms and form elements but returns a JSON data structure.
/// </summary>
/// <returns type="String">A JSON data structure representing the serialized items.</returns>
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.fn["ajaxStart"] = function( f ) {
/// <summary>
/// Attach a function to be executed whenever an AJAX request begins and there is none already active. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return this.bind("ajaxStart", f);
};
jQuery.fn["ajaxStop"] = function( f ) {
/// <summary>
/// Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return this.bind("ajaxStop", f);
};
jQuery.fn["ajaxComplete"] = function( f ) {
/// <summary>
/// Attach a function to be executed whenever an AJAX request completes. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return this.bind("ajaxComplete", f);
};
jQuery.fn["ajaxError"] = function( f ) {
/// <summary>
/// Attach a function to be executed whenever an AJAX request fails. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return this.bind("ajaxError", f);
};
jQuery.fn["ajaxSuccess"] = function( f ) {
/// <summary>
/// Attach a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return this.bind("ajaxSuccess", f);
};
jQuery.fn["ajaxSend"] = function( f ) {
/// <summary>
/// Attach a function to be executed before an AJAX request is sent. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">The function to execute.</param>
/// <returns type="jQuery" />
return this.bind("ajaxSend", f);
};
jQuery.extend({
get: function( url, data, callback, type ) {
/// <summary>
/// Loads a remote page using an HTTP GET request.
/// </summary>
/// <param name="url" type="String">The URL of the HTML page to load.</param>
/// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param>
/// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus) such that this maps the options for this AJAX request.</param>
/// <param name="type" optional="true" type="String">Type of data to be returned to callback function. Valid valiues are xml, html, script, json, text, _default.</param>
/// <returns type="XMLHttpRequest" />
// 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 ) {
/// <summary>
/// Loads and executes a local JavaScript file using an HTTP GET request.
/// </summary>
/// <param name="url" type="String">The URL of the script to load.</param>
/// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(data, textStatus) such that this maps the options for the AJAX request.</param>
/// <returns type="XMLHttpRequest" />
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
/// <summary>
/// Loads JSON data using an HTTP GET request.
/// </summary>
/// <param name="url" type="String">The URL of the JSON data to load.</param>
/// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param>
/// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete if the data is loaded successfully. It should map function(data, textStatus) such that this maps the options for this AJAX request.</param>
/// <returns type="XMLHttpRequest" />
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
/// <summary>
/// Loads a remote page using an HTTP POST request.
/// </summary>
/// <param name="url" type="String">The URL of the HTML page to load.</param>
/// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param>
/// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus) such that this maps the options for this AJAX request.</param>
/// <param name="type" optional="true" type="String">Type of data to be returned to callback function. Valid valiues are xml, html, script, json, text, _default.</param>
/// <returns type="XMLHttpRequest" />
// 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 ) {
/// <summary>
/// Sets up global settings for AJAX requests.
/// </summary>
/// <param name="settings" type="Options">A set of key/value pairs that configure the default Ajax request.</param>
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
username: null,
password: null,
traditional: false,
*/
// This function can be overriden by calling jQuery.ajaxSetup
xhr: function() {
return new window.XMLHttpRequest();
},
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
script: "text/javascript, application/javascript",
json: "application/json, text/javascript",
text: "text/plain",
_default: "*/*"
}
},
ajax: function( origSettings ) {
/// <summary>
/// Load a remote page using an HTTP request.
/// </summary>
/// <private />
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
s.url = s.url.replace( rhash, "" );
// Use original (not extended) context object if it was provided
s.context = origSettings && origSettings.context != null ? origSettings.context : s;
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Handle JSONP Parameter Callbacks
if ( s.dataType === "jsonp" ) {
if ( type === "GET" ) {
if ( !jsre.test( s.url ) ) {
s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
}
} else if ( !s.data || !jsre.test(s.data) ) {
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
}
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = s.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( s.data ) {
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
}
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
var customJsonp = window[ jsonp ];
window[ jsonp ] = function( tmp ) {
if ( jQuery.isFunction( customJsonp ) ) {
customJsonp( tmp );
} else {
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch( jsonpError ) {}
}
data = tmp;
jQuery.handleSuccess( s, xhr, status, data );
jQuery.handleComplete( s, xhr, status, data );
if ( head ) {
head.removeChild( script );
}
};
}
if ( s.dataType === "script" && s.cache === null ) {
s.cache = false;
}
if ( s.cache === false && noContent ) {
var ts = jQuery.now();
// try replacing _= if it is there
var ret = s.url.replace(rts, "$1_=" + ts);
// if nothing was replaced, add timestamp to the end
s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
}
// If data is available, append data to url for GET/HEAD requests
if ( s.data && noContent ) {
s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
}
// Watch for a new set of requests
if ( s.global && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// Matches an absolute URL, and saves the domain
var parts = rurl.exec( s.url ),
remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType === "script" && type === "GET" && remote ) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Handle Script loading
if ( !jsonp ) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
jQuery.handleSuccess( s, xhr, status, data );
jQuery.handleComplete( s, xhr, status, data );
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
// We handle everything using the script element injection
return undefined;
}
var requestDone = false;
// Create the request object
var xhr = s.xhr();
if ( !xhr ) {
return;
}
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open(type, s.url, s.async, s.username, s.password);
} else {
xhr.open(type, s.url, s.async);
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
// Set content-type if data specified and content-body is valid for this type
if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
xhr.setRequestHeader("Content-Type", s.contentType);
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[s.url] ) {
xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
}
if ( jQuery.etag[s.url] ) {
xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
}
}
// Set header so the called script knows that it's an XMLHttpRequest
// Only send the header if it's not a remote XHR
if ( !remote ) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
// Set the Accepts header for the server, depending on the dataType
xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
s.accepts[ s.dataType ] + ", */*; q=0.01" :
s.accepts._default );
} catch( headerError ) {}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
// Handle the global AJAX counter
if ( s.global && jQuery.active-- === 1 ) {
jQuery.event.trigger( "ajaxStop" );
}
// close opended socket
xhr.abort();
return false;
}
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] );
}
// Wait for a response to come back
var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
// The request was aborted
if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
// Opera doesn't call onreadystatechange before this point
// so we simulate the call
if ( !requestDone ) {
jQuery.handleComplete( s, xhr, status, data );
}
requestDone = true;
if ( xhr ) {
xhr.onreadystatechange = jQuery.noop;
}
// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
requestDone = true;
xhr.onreadystatechange = jQuery.noop;
status = isTimeout === "timeout" ?
"timeout" :
!jQuery.httpSuccess( xhr ) ?
"error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
"notmodified" :
"success";
var errMsg;
if ( status === "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch( parserError ) {
status = "parsererror";
errMsg = parserError;
}
}
// Make sure that the request was successful or notmodified
if ( status === "success" || status === "notmodified" ) {
// JSONP handles its own success callback
if ( !jsonp ) {
jQuery.handleSuccess( s, xhr, status, data );
}
} else {
jQuery.handleError( s, xhr, status, errMsg );
}
// Fire the complete handlers
if ( !jsonp ) {
jQuery.handleComplete( s, xhr, status, data );
}
if ( isTimeout === "timeout" ) {
xhr.abort();
}
// Stop memory leaks
if ( s.async ) {
xhr = null;
}
}
};
// Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
// Opera doesn't fire onreadystatechange at all on abort
try {
var oldAbort = xhr.abort;
xhr.abort = function() {
if ( xhr ) {
// oldAbort has no call property in IE7 so
// just do it this way, which works in all
// browsers
Function.prototype.call.call( oldAbort, xhr );
}
onreadystatechange( "abort" );
};
} catch( abortError ) {}
// Timeout checker
if ( s.async && s.timeout > 0 ) {
setTimeout(function() {
// Check to see if the request is still happening
if ( xhr && !requestDone ) {
onreadystatechange( "timeout" );
}
}, s.timeout);
}
// Send the data
try {
xhr.send( noContent || s.data == null ? null : s.data );
} catch( sendError ) {
jQuery.handleError( s, xhr, null, sendError );
// Fire the complete handlers
jQuery.handleComplete( s, xhr, status, data );
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async ) {
onreadystatechange();
}
// return XMLHttpRequest to allow aborting the request etc.
return xhr;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
/// <summary>
/// Create a serialized representation of an array or object, suitable for use in a URL
/// query string or Ajax request.
/// </summary>
/// <param name="a" type="Object">
/// An array or object to serialize.
/// </param>
/// <param name="traditional" type="Boolean">
/// A Boolean indicating whether to perform a traditional "shallow" serialization.
/// </param>
/// <returns type="String" />
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : value;
s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray(a) || a.jquery ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[prefix], traditional, add );
}
}
// Return the resulting serialization
return s.join("&").replace(r20, "+");
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray(obj) && obj.length ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
if ( jQuery.isEmptyObject( obj ) ) {
add( prefix, "" );
// Serialize object item.
} else {
jQuery.each( obj, function( k, v ) {
buildParams( prefix + "[" + k + "]", v, traditional, add );
});
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
handleError: function( s, xhr, status, e ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] );
}
},
handleSuccess: function( s, xhr, status, data ) {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( s.context, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
}
},
handleComplete: function( s, xhr, status ) {
// Process result
if ( s.complete ) {
s.complete.call( s.context, xhr, status );
}
// The request was completed
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] );
}
// Handle the global AJAX counter
if ( s.global && jQuery.active-- === 1 ) {
jQuery.event.trigger( "ajaxStop" );
}
},
triggerGlobal: function( s, type, args ) {
(s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
},
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol === "file:" ||
xhr.status >= 200 && xhr.status < 300 ||
xhr.status === 304 || xhr.status === 1223;
} catch(e) {}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xhr, url ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
var lastModified = xhr.getResponseHeader("Last-Modified"),
etag = xhr.getResponseHeader("Etag");
if ( lastModified ) {
jQuery.lastModified[url] = lastModified;
}
if ( etag ) {
jQuery.etag[url] = etag;
}
return xhr.status === 304;
},
httpData: function( xhr, type, s ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
var ct = xhr.getResponseHeader("content-type") || "",
xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.nodeName === "parsererror" ) {
jQuery.error( "parsererror" );
}
// Allow a pre-filtering function to sanitize the response
// s is checked to keep backwards compatibility
if ( s && s.dataFilter ) {
data = s.dataFilter( data, type );
}
// The filter can actually parse the response
if ( typeof data === "string" ) {
// Get the JavaScript object, if JSON is used.
if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
data = jQuery.parseJSON( data );
// If the type is "script", eval it in global context
} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
jQuery.globalEval( data );
}
}
return data;
}
});
/*
* Create the request object; Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
if ( window.ActiveXObject ) {
jQuery.ajaxSettings.xhr = function() {
if ( window.location.protocol !== "file:" ) {
try {
return new window.XMLHttpRequest();
} catch(xhrError) {}
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(activeError) {}
};
}
// Does this browser support XHR requests?
jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
var elemdisplay = {},
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
jQuery.fn.extend({
show: function( speed, easing, callback ) {
/// <summary>
/// Show all matched elements using a graceful animation and firing an optional callback after completion.
/// </summary>
/// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i];
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery.data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
jQuery.data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[i];
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery.data(elem, "olddisplay") || "";
}
}
return this;
}
},
hide: function( speed, callback ) {
/// <summary>
/// Hides all matched elements using a graceful animation and firing an optional callback after completion.
/// </summary>
/// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" ) {
jQuery.data( this[i], "olddisplay", display );
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
this[i].style.display = "none";
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
/// <summary>
/// Toggles displaying each of the set of matched elements.
/// </summary>
/// <returns type="jQuery" />
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 ) {
/// <summary>
/// Fades the opacity of all matched elements to a specified opacity.
/// </summary>
/// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
/// <summary>
/// A function for making custom animations.
/// </summary>
/// <param name="prop" type="Options">A set of style attributes that you wish to animate and to what end.</param>
/// <param name="speed" optional="true" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="easing" optional="true" type="String">The name of the easing effect that you want to use. There are two built-in values, 'linear' and 'swing'.</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete );
}
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
var opt = jQuery.extend({}, optall), p,
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
self = this;
for ( p in prop ) {
var name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
p = name;
}
if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
return opt.complete.call(this);
}
if ( isElement && ( p === "height" || p === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
var display = defaultDisplay(this.nodeName);
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
if ( jQuery.isArray( prop[p] ) ) {
// Create (if needed) and add to specialEasing
(opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
prop[p] = prop[p][0];
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
opt.curAnim = jQuery.extend({}, prop);
jQuery.each( prop, function( name, val ) {
var e = new jQuery.fx( self, opt, name );
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );
} else {
var parts = rfxnum.exec(val),
start = e.cur() || 0;
if ( parts ) {
var end = parseFloat( parts[2] ),
unit = parts[3] || "px";
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( self, name, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( self, name, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
});
// For JS strict compliance
return true;
});
},
stop: function( clearQueue, gotoEnd ) {
/// <summary>
/// Stops all currently animations on the specified elements.
/// </summary>
/// <param name="clearQueue" optional="true" type="Boolean">True to clear animations that are queued to run.</param>
/// <param name="gotoEnd" optional="true" type="Boolean">True to move the element value to the end of its animation target.</param>
/// <returns type="jQuery" />
var timers = jQuery.timers;
if ( clearQueue ) {
this.queue([]);
}
this.each(function() {
// go in reverse order so anything added to the queue during the loop is ignored
for ( var i = timers.length - 1; i >= 0; i-- ) {
if ( timers[i].elem === this ) {
if (gotoEnd) {
// force the next step to be the last
timers[i](true);
}
timers.splice(i, 1);
}
}
});
// start the next in the queue if the last step wasn't forced
if ( !gotoEnd ) {
this.dequeue();
}
return this;
}
});
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
// jQuery.each({
// slideDown: genFx("show", 1),
// slideUp: genFx("hide", 1),
// slideToggle: genFx("toggle", 1),
// fadeIn: { opacity: "show" },
// fadeOut: { opacity: "hide" },
// fadeToggle: { opacity: "toggle" }
// }, function( name, props ) {
// jQuery.fn[ name ] = function( speed, easing, callback ) {
// return this.animate( props, speed, easing, callback );
// };
// });
jQuery.fn[ "slideDown" ] = function( speed, callback ) {
/// <summary>
/// Reveal all matched elements by adjusting their height.
/// </summary>
/// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
return this.animate( genFx("show", 1), speed, callback );
};
jQuery.fn[ "slideUp" ] = function( speed, callback ) {
/// <summary>
/// Hiding all matched elements by adjusting their height.
/// </summary>
/// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
return this.animate( genFx("hide", 1), speed, callback );
};
jQuery.fn[ "slideToggle" ] = function( speed, callback ) {
/// <summary>
/// Toggles the visibility of all matched elements by adjusting their height.
/// </summary>
/// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
return this.animate( genFx("toggle", 1), speed, callback );
};
jQuery.fn[ "fadeIn" ] = function( speed, callback ) {
/// <summary>
/// Fades in all matched elements by adjusting their opacity.
/// </summary>
/// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
return this.animate( { opacity: "show" }, speed, callback );
};
jQuery.fn[ "fadeOut" ] = function( speed, callback ) {
/// <summary>
/// Fades the opacity of all matched elements to a specified opacity.
/// </summary>
/// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
/// the number of milliseconds to run the animation</param>
/// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param>
/// <returns type="jQuery" />
return this.animate( { opacity: "hide" }, speed, callback );
};
jQuery.extend({
speed: function( speed, easing, fn ) {
/// <summary>
/// This member is internal.
/// </summary>
/// <private />
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( opt.queue !== false ) {
jQuery(this).dequeue();
}
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
/// <summary>
/// This member is internal.
/// </summary>
/// <private />
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
/// <summary>
/// This member is internal.
/// </summary>
/// <private />
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
/// <summary>
/// This member is internal.
/// </summary>
/// <private />
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() {
/// <summary>
/// This member is internal.
/// </summary>
/// <private />
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() {
/// <summary>
/// This member is internal.
/// </summary>
/// <private />
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
return this.elem[ this.prop ];
}
var r = parseFloat( jQuery.css( this.elem, this.prop ) );
return r && r > -10000 ? r : 0;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = jQuery.now();
this.start = from;
this.end = to;
this.unit = unit || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval(fx.tick, fx.interval);
}
},
// Simple 'show' function
show: function() {
/// <summary>
/// Displays each of the set of matched elements if they are hidden.
/// </summary>
// 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() {
/// <summary>
/// Hides each of the set of matched elements if they are shown.
/// </summary>
// 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 ) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
var t = jQuery.now(), done = true;
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
for ( var i in this.options.curAnim ) {
if ( this.options.curAnim[i] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
var elem = this.elem,
options = this.options;
jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index];
} );
}
// Hide the element if the "hide" operation was done
if ( this.options.hide ) {
jQuery(this.elem).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( this.options.hide || this.options.show ) {
for ( var p in this.options.curAnim ) {
jQuery.style( this.elem, p, this.options.orig[p] );
}
}
// Execute the complete function
this.options.complete.call( this.elem );
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
// Perform the easing function, defaults to swing
var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ ) {
if ( !timers[i]() ) {
timers.splice(i--, 1);
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var elem = jQuery("<" + nodeName + ">").appendTo("body"),
display = elem.css("display");
elem.remove();
if ( display === "none" || display === "" ) {
display = "block";
}
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
/// <summary>
/// Set the current coordinates of every element in the set of matched elements,
/// relative to the document.
/// </summary>
/// <param name="options" type="Object">
/// An object containing the properties top and left, which are integers indicating the
/// new top and left coordinates for the elements.
/// </param>
/// <returns type="jQuery" />
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box || { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ),
scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
/// <summary>
/// Set the current coordinates of every element in the set of matched elements,
/// relative to the document.
/// </summary>
/// <param name="options" type="Object">
/// An object containing the properties top and left, which are integers indicating the
/// new top and left coordinates for the elements.
/// </param>
/// <returns type="jQuery" />
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
jQuery.offset.initialize();
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
initialize: function() {
var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
container.innerHTML = html;
body.insertBefore( container, body.firstChild );
innerDiv = container.firstChild;
checkDiv = innerDiv.firstChild;
td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
checkDiv.style.position = "fixed";
checkDiv.style.top = "20px";
// safari subtracts parent border width here which is 5px
this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
checkDiv.style.position = checkDiv.style.top = "";
innerDiv.style.overflow = "hidden";
innerDiv.style.position = "relative";
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
body.removeChild( container );
body = container = innerDiv = checkDiv = table = td = null;
jQuery.offset.initialize = jQuery.noop;
},
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
jQuery.offset.initialize();
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1),
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is absolute
if ( calculatePosition ) {
curPosition = curElem.position();
}
curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0;
curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0;
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if (options.top != null) {
props.top = (options.top - curOffset.top) + curTop;
}
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
/// <summary>
/// Gets the top and left positions of an element relative to its offset parent.
/// </summary>
/// <returns type="Object">An object with two integer properties, 'top' and 'left'.</returns>
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() {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function(val) {
/// <summary>
/// Gets and optionally sets the scroll left offset of the first matched element.
/// </summary>
/// <param name="val" type="Number" integer="true" optional="true">A positive number representing the desired scroll left offset.</param>
/// <returns type="Number" integer="true">The scroll left offset of the first matched element.</returns>
var elem = this[0], win;
if ( !elem ) {
return null;
}
if ( val !== undefined ) {
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery(win).scrollLeft(),
i ? val : jQuery(win).scrollTop()
);
} else {
this[ method ] = val;
}
});
} else {
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function() {
/// <summary>
/// Gets the inner height of the first matched element, excluding border but including padding.
/// </summary>
/// <returns type="Number" integer="true">The outer height of the first matched element.</returns>
return this[0] ?
parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function( margin ) {
/// <summary>
/// Gets the outer height of the first matched element, including border and padding by default.
/// </summary>
/// <param name="margins" type="Map">A set of key/value pairs that specify the options for the method.</param>
/// <returns type="Number" integer="true">The outer height of the first matched element.</returns>
return this[0] ?
parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.fn[ type ] = function( size ) {
/// <summary>
/// Set the CSS height of every matched element. If no explicit unit
/// was specified (like 'em' or '%') then "px" is added to the width. If no parameter is specified, it gets
/// the current computed pixel height of the first matched element.
/// Part of CSS
/// </summary>
/// <returns type="jQuery" type="jQuery" />
/// <param name="cssProperty" type="String">
/// Set the CSS property to the specified value. Omit to get the value of the first matched element.
/// </param>
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
elem.document.body[ "client" + name ];
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function() {
/// <summary>
/// Gets the inner width of the first matched element, excluding border but including padding.
/// </summary>
/// <returns type="Number" integer="true">The outer width of the first matched element.</returns>
return this[0] ?
parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function( margin ) {
/// <summary>
/// Gets the outer width of the first matched element, including border and padding by default.
/// </summary>
/// <param name="margin" type="Map">A set of key/value pairs that specify the options for the method.</param>
/// <returns type="Number" integer="true">The outer width of the first matched element.</returns>
return this[0] ?
parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.fn[ type ] = function( size ) {
/// <summary>
/// Set the CSS width of every matched element. If no explicit unit
/// was specified (like 'em' or '%') then "px" is added to the width. If no parameter is specified, it gets
/// the current computed pixel width of the first matched element.
/// Part of CSS
/// </summary>
/// <returns type="jQuery" type="jQuery" />
/// <param name="cssProperty" type="String">
/// Set the CSS property to the specified value. Omit to get the value of the first matched element.
/// </param>
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
elem.document.body[ "client" + name ];
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
})(window);
|
pootle/static/js/auth/components/SignInForm.js | phlax/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import assign from 'object-assign';
import React from 'react';
import { gotoScreen, signIn } from '../actions';
import FormElement from 'components/FormElement';
import FormMixin from 'mixins/FormMixin';
const SignInForm = React.createClass({
propTypes: {
canRegister: React.PropTypes.bool.isRequired,
dispatch: React.PropTypes.func.isRequired,
formErrors: React.PropTypes.object.isRequired,
isLoading: React.PropTypes.bool.isRequired,
},
mixins: [FormMixin],
/* Lifecycle */
getInitialState() {
// XXX: initialData required by `FormMixin`; this is really OBSCURE
this.initialData = {
login: '',
password: '',
};
return {
formData: assign({}, this.initialData),
};
},
componentWillReceiveProps(nextProps) {
if (this.state.errors !== nextProps.formErrors) {
this.setState({ errors: nextProps.formErrors });
}
},
/* Handlers */
handleRequestPasswordReset(e) {
e.preventDefault();
this.props.dispatch(gotoScreen('requestPasswordReset'));
},
handleSignUp(e) {
e.preventDefault();
this.props.dispatch(gotoScreen('signUp'));
},
handleFormSubmit(e) {
e.preventDefault();
const nextURL = window.location.pathname + window.location.hash;
this.props.dispatch(signIn(this.state.formData, nextURL));
},
/* Others */
hasData() {
const { formData } = this.state;
return formData.login !== '' && formData.password !== '';
},
/* Layout */
render() {
const { errors } = this.state;
const { formData } = this.state;
const signUp = this.props.canRegister ?
<a href="#" onClick={this.handleSignUp}>
{gettext('Sign up as a new user')}
</a> :
<p>{gettext('Creating new user accounts is prohibited.')}</p>;
return (
<form
method="post"
onSubmit={this.handleFormSubmit}
>
<div className="fields">
<FormElement
autoFocus
label={gettext('Username')}
handleChange={this.handleChange}
name="login"
errors={errors.login}
value={formData.login}
dir="ltr"
/>
<FormElement
type="password"
label={gettext('Password')}
handleChange={this.handleChange}
name="password"
errors={errors.password}
value={formData.password}
dir="ltr"
/>
<div className="actions password-forgotten">
<a href="#" onClick={this.handleRequestPasswordReset}>
{gettext('I forgot my password')}
</a>
</div>
{this.renderAllFormErrors()}
</div>
<div className="actions">
<div>
<input
type="submit"
className="btn btn-primary"
disabled={!this.hasData() || this.props.isLoading}
value={gettext('Sign In')}
/>
</div>
<div>
{signUp}
</div>
</div>
</form>
);
},
});
export default SignInForm;
|
src/svg-icons/action/book.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionBook = (props) => (
<SvgIcon {...props}>
<path d="M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 4h5v8l-2.5-1.5L6 12V4z"/>
</SvgIcon>
);
ActionBook = pure(ActionBook);
ActionBook.displayName = 'ActionBook';
ActionBook.muiName = 'SvgIcon';
export default ActionBook;
|
src/components/Bio.js | aravindballa/website2017 | import React from 'react';
import profilePic from './profile-pic.jpg';
class Bio extends React.Component {
render() {
return (
<div className="flex py-6 mt-8 border-t-2 border-gray-500 items-center">
<img className="rounded-full w-16 h-16" src="/avatar.jpg" alt={`Aravind Balla`} />
<p className="text-green ml-6">
By <strong>Aravind Balla</strong> who is a friendly human, building things for himself,
and sometimes for others.{' '}
<a
className="text-green dark:text-green"
href="https://twitter.com/aravindballa"
target="_blank"
>
You should hit him up on Twitter!
</a>
</p>
</div>
);
}
}
export default Bio;
|
src/components/TaskbarWindowsList/TaskbarWindowsList.js | z81/PolarOS_Next | import React, { PropTypes, Component } from 'react'
import styles from './TaskbarWindowsList.scss'
class TaskbarWindowsList extends Component {
static propTypes = {
position: PropTypes.any,
windows: PropTypes.any,
onActive: PropTypes.any
};
constructor (props) {
super(props)
this.state = {}
}
_selectWindow (id) {
if (this.props.onActive) {
this.props.onActive(id)
}
}
render () {
return (
<span className={styles.windows}>
{!this.props.windows || this.props.windows.list.map((w, i) => {
return <span onClick={this._selectWindow.bind(this, w.id)} key={i} className={styles.win}>{w.title}</span>
})}
</span>
)
}
}
export default TaskbarWindowsList
|
ajax/libs/6to5/2.13.2/browser-polyfill.js | yukinying/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){"use strict";require("core-js/shim");require("regenerator/runtime")},{"core-js/shim":2,"regenerator/runtime":3}],2:[function(require,module,exports){!function(global,framework,undefined){"use strict";var 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,apply=FunctionProto.apply,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)}function construct(target,argumentsList){var instance=create((arguments.length<3?target:assertFunction(arguments[2]))[PROTOTYPE]),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,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 toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}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=toObject(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){var O=Object(assertDefined(this)),that=arguments[1],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){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],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 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({},DOT,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_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{};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;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.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,exportGlobal,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(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||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);DESC&&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),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,"+"species,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(GLOBAL,{Reflect:{ownKeys:ownKeys}})}(safeSymbol("tag"),{},true);!function(RegExpProto,isFinite,tmp,NAME){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(x){return(x=+x)==0||x!=x?x:x<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=setPrototypeOf=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=+x)<1?NaN:log(x+sqrt(x*x-1))},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+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=+x)+exp(-x))/2},expm1:function(x){return(x=+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,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+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=+x)==0?x:(exp(x)-exp(-x))/2},tanh:function(x){return isFinite(x=+x)?x==0?x:(exp(x)-exp(-x))/(exp(x)+exp(-x)):sign(x)},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){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=toObject(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){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},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){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.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){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapfn=arguments[1],that=arguments[2],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){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],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){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],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:toObject(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);function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames");if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});NAME in FunctionProto||defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}});var _RegExp=RegExp;var WrappedRegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};if(DESC&&!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){forEach.call(getNames(RegExp),function(key){key in WrappedRegExp||defineProperty(WrappedRegExp,key,{configurable:true,get:function(){return RegExp[key]},set:function(it){RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=WrappedRegExp;WrappedRegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,WrappedRegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")});forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}}(RegExp[PROTOTYPE],isFinite,{},"name");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,!isMap);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){var f=ctx(callbackfn,arguments[1],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(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return desc.get?desc.get.call(receiver):desc.value;return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc){if(desc.writable===false)return false;if(desc.set)return desc.set.call(receiver,V),true}if(isObject(proto=getPrototypeOf(target)))return reflectSet(proto,propertyKey,V,receiver);desc=getOwnDescriptor(receiver,propertyKey)||descriptor(0);desc.value=V;return defineProperty(receiver,propertyKey,desc),true}var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:getOwnDescriptor,getPrototypeOf:getPrototypeOf,has:function(target,propertyKey){return propertyKey in target},isExtensible:Object.isExtensible||function(target){return!!assertObject(target)},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true
};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(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(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[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");$define(STATIC,ARRAY,arrayStatics)}({})}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),true)},{}],3:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}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){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.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){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;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;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}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,next=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}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[1]); |
__tests__/react-component-tests/isRequiredIf-number-proptype-test.js | evcohen/react-proptype-conditional-require | /* eslint-env mocha */
import assert from 'assert';
import { createRenderer } from 'react-addons-test-utils';
import { sandbox } from 'sinon';
import React from 'react';
import PropTypes from 'prop-types';
import isRequiredIf from '../../isRequiredIf';
const { number } = PropTypes;
describe('React component number proptype tests', () => {
let fixtures = {};
beforeEach(() => {
fixtures.renderer = createRenderer();
fixtures.Component = props => <div>Hello {props.value}</div>; // eslint-disable-line
fixtures.sandbox = sandbox.create();
fixtures.warn = fixtures.sandbox.stub(console, 'error').throws();
});
afterEach(() => {
fixtures.sandbox.restore();
fixtures = {};
});
it(
'...prop is not required and present, so it ' +
'validates against React number propType',
() => {
const {
renderer,
Component,
} = fixtures;
Component.propTypes = {
value: isRequiredIf(number, false),
};
assert.doesNotThrow(
() => {
renderer.render(<Component value={42} />);
},
undefined,
);
},
);
it(
'...prop is not required and missing, so it ' +
'validates against React number propType',
() => {
const {
renderer,
Component,
} = fixtures;
Component.propTypes = {
value: isRequiredIf(number, false),
};
assert.doesNotThrow(
() => {
renderer.render(<Component />);
},
undefined,
);
},
);
it(
'...prop is required and warns because it is missing',
() => {
const {
renderer,
Component,
} = fixtures;
Component.propTypes = {
value: isRequiredIf(number, true),
};
assert.throws(
() => {
renderer.render(<Component />);
},
Error,
'Throws because required prop is missing.',
);
},
);
it(
'...prop is required and present so it validates against the number',
() => {
const {
renderer,
Component,
} = fixtures;
Component.propTypes = {
value: isRequiredIf(number, true),
};
assert.doesNotThrow(
() => {
renderer.render(<Component value={42} />);
},
undefined,
);
},
);
});
|
blueprints/smart/files/__root__/containers/__name__.js | llukasxx/school-organizer-front | import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
type Props = {
}
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render() {
return (
<div></div>
)
}
}
const mapStateToProps = (state) => {
return {}
}
const mapDispatchToProps = (dispatch) => {
return {}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(<%= pascalEntityName %>)
|
node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | andrewpen/apendleton | 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'));
|
options/root.js | voz-living/chrome-extension-react | import React from 'react';
import { render } from 'react-dom';
import OptionPage from './OptionPage';
render(<OptionPage />, document.getElementById('root'));
|
examples/component-as-body/components/HelloWorld.js | chentsulin/sweetalert-react | import React from 'react';
const HelloWorld = () => <h1>SweetAlert in React</h1>;
export default HelloWorld;
|
media/k2/assets/js/jquery-1.6.4.min.js | adrian2020my/gavick | /*! jQuery v1.6.4 http://jquery.com/ | http://jquery.org/license */
(function(a,b){function cu(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cr(a){if(!cg[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ch||(ch=c.createElement("iframe"),ch.frameBorder=ch.width=ch.height=0),b.appendChild(ch);if(!ci||!ch.createElement)ci=(ch.contentWindow||ch.contentDocument).document,ci.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),ci.close();d=ci.createElement(a),ci.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ch)}cg[a]=e}return cg[a]}function cq(a,b){var c={};f.each(cm.concat.apply([],cm.slice(0,b)),function(){c[this]=a});return c}function cp(){cn=b}function co(){setTimeout(cp,0);return cn=f.now()}function cf(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ce(){try{return new a.XMLHttpRequest}catch(b){}}function b$(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 bZ(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 bY(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bA.test(a)?d(a,e):bY(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)bY(a+"["+e+"]",b[e],c,d);else d(a,b)}function bX(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 bW(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===bP,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=bW(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bW(a,c,d,e,"*",g));return l}function bV(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bL),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 by(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bt:bu;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=bv(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 bl(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bd,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bk(a){f.nodeName(a,"input")?bj(a):"getElementsByTagName"in a&&f.grep(a.getElementsByTagName("input"),bj)}function bj(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bi(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bh(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 bg(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c=f.expando,d=f.data(a),e=f.data(b,d);if(d=d[c]){var g=d.events;e=e[c]=f.extend({},d);if(g){delete e.handle,e.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)f.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function bf(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function V(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(Q.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 U(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function M(a,b){return(a&&a!=="*"?a+".":"")+b.replace(y,"`").replace(z,"&")}function L(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(w,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function J(a,c,d){var e=f.extend({},d[0]);e.type=a,e.originalEvent={},e.liveFired=b,f.event.handle.call(c,e),e.isDefaultPrevented()&&d[0].preventDefault()}function D(){return!0}function C(){return!1}function m(a,c,d){var e=c+"defer",g=c+"queue",h=c+"mark",i=f.data(a,e,b,!0);i&&(d==="queue"||!f.data(a,g,b,!0))&&(d==="mark"||!f.data(a,h,b,!0))&&setTimeout(function(){!f.data(a,g,b,!0)&&!f.data(a,h,b,!0)&&(f.removeData(a,e,!0),i.resolve())},0)}function l(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function k(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(j,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNaN(d)?i.test(d)?f.parseJSON(d):d:parseFloat(d)}catch(g){}f.data(a,c,d)}else d=b}return d}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.6.4",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.done(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.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e._Deferred();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},isNaN: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){if(!b)return-1;if(I)return I.call(b,a);for(var c=0,d=b.length;c<d;c++)if(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())});return e}(),g="done fail isResolved isRejected promise then always pipe".split(" "),h=[].slice;f.extend({_Deferred:function(){var a=[],b,c,d,e={done:function(){if(!d){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=f.type(i),j==="array"?e.done.apply(e,i):j==="function"&&a.push(i);k&&e.resolveWith(k[0],k[1])}return this},resolveWith:function(e,f){if(!d&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(e,f)}finally{b=[e,f],c=0}}return this},resolve:function(){e.resolveWith(this,arguments);return this},isResolved:function(){return!!c||!!b},cancel:function(){d=1,a=[];return this}};return e},Deferred:function(a){var b=f._Deferred(),c=f._Deferred(),d;f.extend(b,{then:function(a,c){b.done(a).fail(c);return this},always:function(){return b.done.apply(b,arguments).fail.apply(this,arguments)},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,pipe:function(a,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[c,"reject"]},function(a,c){var e=c[0],g=c[1],h;f.isFunction(e)?b[a](function(){h=e.apply(this,arguments),h&&f.isFunction(h.promise)?h.promise().then(d.resolve,d.reject):d[g+"With"](this===b?d:this,[h])}):b[a](d[g])})}).promise()},promise:function(a){if(a==null){if(d)return d;d=a={}}var c=g.length;while(c--)a[g[c]]=b[g[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?h.call(arguments,0):c,--e||g.resolveWith(g,h.call(b,0))}}var b=arguments,c=0,d=b.length,e=d,g=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred();if(d>1){for(;c<d;c++)b[c]&&f.isFunction(b[c].promise)?b[c].promise().then(i(c),g.reject):--e;e||g.resolveWith(g,b)}else g!==a&&g.resolveWith(g,d?[a]:[]);return g.promise()}}),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'/>",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,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",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.firstChild),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:"-1000px",top:"-1000px"});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),o.innerHTML="",n.removeChild(o);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;o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var i=/^(?:\{.*\}|\[.*\])$/,j=/([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&&!l(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i=f.expando,j=typeof c=="string",k=a.nodeType,l=k?f.cache:a,m=k?a[f.expando]:a[f.expando]&&f.expando;if((!m||e&&m&&l[m]&&!l[m][i])&&j&&d===b)return;m||(k?a[f.expando]=m=++f.uuid:m=f.expando),l[m]||(l[m]={},k||(l[m].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?l[m][i]=f.extend(l[m][i],c):l[m]=f.extend(l[m],c);g=l[m],e&&(g[i]||(g[i]={}),g=g[i]),d!==b&&(g[f.camelCase(c)]=d);if(c==="events"&&!g[c])return g[i]&&g[i].events;j?(h=g[c],h==null&&(h=g[f.camelCase(c)])):h=g;return h}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e=f.expando,g=a.nodeType,h=g?f.cache:a,i=g?a[f.expando]:f.expando;if(!h[i])return;if(b){d=c?h[i][e]:h[i];if(d){d[b]||(b=f.camelCase(b)),delete d[b];if(!l(d))return}}if(c){delete h[i][e];if(!l(h[i]))return}var j=h[i][e];f.support.deleteExpando||!h.setInterval?delete h[i]:h[i]=null,j?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=j):g&&(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=null;if(typeof a=="undefined"){if(this.length){d=f.data(this[0]);if(this[0].nodeType===1){var e=this[0].attributes,g;for(var h=0,i=e.length;h<i;h++)g=e[h].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),k(this[0],g,d[g]))}}return d}if(typeof a=="object")return this.each(function(){f.data(this,a)});var j=a.split(".");j[1]=j[1]?"."+j[1]:"";if(c===b){d=this.triggerHandler("getData"+j[1]+"!",[j[0]]),d===b&&this.length&&(d=f.data(this[0],a),d=k(this[0],a,d));return d===b&&j[1]?this.data(j[0]):d}return this.each(function(){var b=f(this),d=[j[0],c];b.triggerHandler("setData"+j[1]+"!",d),f.data(this,a,c),b.triggerHandler("changeData"+j[1]+"!",d)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,c){a&&(c=(c||"fx")+"mark",f.data(a,c,(f.data(a,c,b,!0)||0)+1,!0))},_unmark:function(a,c,d){a!==!0&&(d=c,c=a,a=!1);if(c){d=d||"fx";var e=d+"mark",g=a?0:(f.data(c,e,b,!0)||1)-1;g?f.data(c,e,g,!0):(f.removeData(c,e,!0),m(c,d,"mark"))}},queue:function(a,c,d){if(a){c=(c||"fx")+"queue";var e=f.data(a,c,b,!0);d&&(!e||f.isArray(d)?e=f.data(a,c,f.makeArray(d),!0):e.push(d));return e||[]}},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"),d.call(a,function(){f.dequeue(a,b)})),c.length||(f.removeData(a,b+"queue",!0),m(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(){var c=this;setTimeout(function(){f.dequeue(c,b)},a)})},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._Deferred(),!0))h++,l.done(m);m();return d.promise()}});var n=/[\n\t\r]/g,o=/\s+/,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,v;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(o);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(o);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(n," ");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(o);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+" ";for(var c=0,d=this.length;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(n," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e=this[0];if(!arguments.length){if(e){c=f.valHooks[e.nodeName.toLowerCase()]||f.valHooks[e.type];if(c&&"get"in c&&(d=c.get(e,"value"))!==b)return d;d=e.value;return typeof d=="string"?d.replace(p,""):d==null?"":d}return b}var g=f.isFunction(a);return this.each(function(d){var e=f(this),h;if(this.nodeType===1){g?h=a.call(this,d,e.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=a.selectedIndex,d=[],e=a.options,g=a.type==="select-one";if(c<0)return null;for(var h=g?c:0,i=g?c+1:e.length;h<i;h++){var j=e[h];if(j.selected&&(f.support.optDisabled?!j.disabled:j.getAttribute("disabled")===null)&&(!j.parentNode.disabled||!f.nodeName(j.parentNode,"optgroup"))){b=f(j).val();if(g)return b;d.push(b)}}if(g&&!d.length&&e.length)return f(e[c]).val();return d},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},attrFix:{tabindex:"tabIndex"},attr:function(a,c,d,e){var g=a.nodeType;if(!a||g===3||g===8||g===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);var h,i,j=g!==1||!f.isXMLDoc(a);j&&(c=f.attrFix[c]||c,i=f.attrHooks[c],i||(t.test(c)?i=v:u&&(i=u)));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(i&&"set"in i&&j&&(h=i.set(a,d,c))!==b)return h;a.setAttribute(c,""+d);return d}if(i&&"get"in i&&j&&(h=i.get(a,c))!==null)return h;h=a.getAttribute(c);return h===null?b:h},removeAttr:function(a,b){var c;a.nodeType===1&&(b=f.attrFix[b]||b,f.attr(a,b,""),a.removeAttribute(b),t.test(b)&&(c=f.propFix[b]||b)in a&&(a[c]=!1))},attrHooks:{type:{set:function(a,b){if(q.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(u&&f.nodeName(a,"button"))return u.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(u&&f.nodeName(a,"button"))return u.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=a.nodeType;if(!a||e===3||e===8||e===2)return b;var g,h,i=e!==1||!f.isXMLDoc(a);i&&(c=f.propFix[c]||c,h=f.propHooks[c]);return d!==b?h&&"set"in h&&(g=h.set(a,d,c))!==b?g:a[c]=d:h&&"get"in h&&(g=h.get(a,c))!==null?g: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}}}}),f.attrHooks.tabIndex=f.propHooks.tabIndex,v={get:function(a,c){var d;return f.prop(a,c)===!0||(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}},f.support.getSetAttribute||(u=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?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.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.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.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 w=/\.(.*)$/,x=/^(?:textarea|input|select)$/i,y=/\./g,z=/ /g,A=/[^\w\s.|`]/g,B=function(a){return a.replace(A,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=C;else if(!d)return;var g,h;d.handler&&(g=d,d=g.handler),d.guid||(d.guid=f.guid++);var i=f._data(a);if(!i)return;var j=i.events,k=i.handle;j||(i.events=j={}),k||(i.handle=k=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.handle.apply(k.elem,arguments):b}),k.elem=a,c=c.split(" ");var l,m=0,n;while(l=c[m++]){h=g?f.extend({},g):{handler:d,data:e},l.indexOf(".")>-1?(n=l.split("."),l=n.shift(),h.namespace=n.slice(0).sort().join(".")):(n=[],h.namespace=""),h.type=l,h.guid||(h.guid=d.guid);var o=j[l],p=f.event.special[l]||{};if(!o){o=j[l]=[];if(!p.setup||p.setup.call(a,e,n,k)===!1)a.addEventListener?a.addEventListener(l,k,!1):a.attachEvent&&a.attachEvent("on"+l,k)}p.add&&(p.add.call(a,h),h.handler.guid||(h.handler.guid=d.guid)),o.push(h),f.event.global[l]=!0}a=null}},global:{},remove:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){d===!1&&(d=C);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=f.hasData(a)&&f._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(d=c.handler,c=c.type);if(!c||typeof c=="string"&&c.charAt(0)==="."){c=c||"";for(h in t)f.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+f.map(m.slice(0).sort(),B).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!d){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))f.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=f.event.special[h]||{};for(j=e||0;j<p.length;j++){q=p[j];if(d.guid===q.guid){if(l||n.test(q.namespace))e==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(e!=null)break}}if(p.length===0||e!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&f.removeEvent(a,h,s.handle),g=null,delete
t[h]}if(f.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,f.isEmptyObject(s)&&f.removeData(a,b,!0)}}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){var h=c.type||c,i=[],j;h.indexOf("!")>=0&&(h=h.slice(0,-1),j=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if(!!e&&!f.event.customEvent[h]||!!f.event.global[h]){c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.exclusive=j,c.namespace=i.join("."),c.namespace_re=new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)");if(g||!e)c.preventDefault(),c.stopPropagation();if(!e){f.each(f.cache,function(){var a=f.expando,b=this[a];b&&b.events&&b.events[h]&&f.event.trigger(c,d,b.handle.elem)});return}if(e.nodeType===3||e.nodeType===8)return;c.result=b,c.target=e,d=d!=null?f.makeArray(d):[],d.unshift(c);var k=e,l=h.indexOf(":")<0?"on"+h:"";do{var m=f._data(k,"handle");c.currentTarget=k,m&&m.apply(k,d),l&&f.acceptData(k)&&k[l]&&k[l].apply(k,d)===!1&&(c.result=!1,c.preventDefault()),k=k.parentNode||k.ownerDocument||k===c.target.ownerDocument&&a}while(k&&!c.isPropagationStopped());if(!c.isDefaultPrevented()){var n,o=f.event.special[h]||{};if((!o._default||o._default.call(e.ownerDocument,c)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)){try{l&&e[h]&&(n=e[l],n&&(e[l]=null),f.event.triggered=h,e[h]())}catch(p){}n&&(e[l]=n),f.event.triggered=b}}return c.result}},handle:function(c){c=f.event.fix(c||a.event);var d=((f._data(this,"events")||{})[c.type]||[]).slice(0),e=!c.exclusive&&!c.namespace,g=Array.prototype.slice.call(arguments,0);g[0]=c,c.currentTarget=this;for(var h=0,i=d.length;h<i;h++){var j=d[h];if(e||c.namespace_re.test(j.namespace)){c.handler=j.handler,c.data=j.data,c.handleObj=j;var k=j.handler.apply(this,g);k!==b&&(c.result=k,k===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[f.expando])return a;var d=a;a=f.Event(d);for(var e=this.props.length,g;e;)g=this.props[--e],a[g]=d[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=a.target.ownerDocument||c,i=h.documentElement,j=h.body;a.pageX=a.clientX+(i&&i.scrollLeft||j&&j.scrollLeft||0)-(i&&i.clientLeft||j&&j.clientLeft||0),a.pageY=a.clientY+(i&&i.scrollTop||j&&j.scrollTop||0)-(i&&i.clientTop||j&&j.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:f.proxy,special:{ready:{setup:f.bindReady,teardown:f.noop},live:{add:function(a){f.event.add(this,M(a.origType,a.selector),f.extend({},a,{handler:L,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,M(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},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.preventDefault)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()?D:C):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=D;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=D;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=D,this.stopPropagation()},isDefaultPrevented:C,isPropagationStopped:C,isImmediatePropagationStopped:C};var E=function(a){var b=a.relatedTarget,c=!1,d=a.type;a.type=a.data,b!==this&&(b&&(c=f.contains(this,b)),c||(f.event.handle.apply(this,arguments),a.type=d))},F=function(a){a.type=a.data,f.event.handle.apply(this,arguments)};f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={setup:function(c){f.event.add(this,b,c&&c.selector?F:E,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?F:E)}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(a,b){if(!f.nodeName(this,"form"))f.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=f.nodeName(b,"input")||f.nodeName(b,"button")?b.type:"";(c==="submit"||c==="image")&&f(b).closest("form").length&&J("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=f.nodeName(b,"input")||f.nodeName(b,"button")?b.type:"";(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&J("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var G,H=function(a){var b=f.nodeName(a,"input")?a.type:"",c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?f.map(a.options,function(a){return a.selected}).join("-"):"":f.nodeName(a,"select")&&(c=a.selectedIndex);return c},I=function(c){var d=c.target,e,g;if(!!x.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=H(d),(c.type!=="focusout"||d.type!=="radio")&&f._data(d,"_change_data",g);if(e===b||g===e)return;if(e!=null||g)c.type="change",c.liveFired=b,f.event.trigger(c,arguments[1],d)}};f.event.special.change={filters:{focusout:I,beforedeactivate:I,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&I.call(this,a)},keydown:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(a.keyCode===13&&!f.nodeName(b,"textarea")||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&I.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",H(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in G)f.event.add(this,c+".specialChange",G[c]);return x.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return x.test(this.nodeName)}},G=f.event.special.change.filters,G.focus=G.beforeactivate}f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){function e(a){var c=f.event.fix(a);c.type=b,c.originalEvent={},f.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var d=0;f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.each(["bind","one"],function(a,c){f.fn[c]=function(a,d,e){var g;if(typeof a=="object"){for(var h in a)this[c](h,d,a[h],e);return this}if(arguments.length===2||d===!1)e=d,d=b;c==="one"?(g=function(a){f(this).unbind(a,g);return e.apply(this,arguments)},g.guid=e.guid||f.guid++):g=e;if(a==="unload"&&c!=="one")this.one(a,d,e);else for(var i=0,j=this.length;i<j;i++)f.event.add(this[i],a,g,d);return this}}),f.fn.extend({unbind:function(a,b){if(typeof a=="object"&&!a.preventDefault)for(var c in a)this.unbind(c,a[c]);else for(var d=0,e=this.length;d<e;d++)f.event.remove(this[d],a,b);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},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)}});var K={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};f.each(["live","die"],function(a,c){f.fn[c]=function(a,d,e,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:f(this.context);if(typeof a=="object"&&!a.preventDefault){for(var o in a)n[c](o,d,a[o],m);return this}if(c==="die"&&!a&&g&&g.charAt(0)==="."){n.unbind(g);return this}if(d===!1||f.isFunction(d))e=d||C,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=w.exec(h),k="",j&&(k=j[0],h=h.replace(w,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,K[h]?(a.push(K[h]+k),h=h+k):h=(K[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+M(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+M(h,m),e)}return this}}),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".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)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d=0,e=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,f,g){f=f||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return f;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(e.call(n)==="[object Array]")if(!u)f.push.apply(f,n);else if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&f.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&f.push(j[t]);else p(n,f);o&&(k(o,h,f,g),k.uniqueSort(f));return f};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(!f)g=o=!0;else if(f===!0)continue}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.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&&!j.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&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!j.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&&k.filter(b,a,!0)}},"":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("parentNode",b,f,a,e,c)},"~":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("previousSibling",b,f,a,e,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(i,"")+" ";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(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.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]&&k.error(a[0]);a[0]=d++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),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]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.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!!k(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=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([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}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||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=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":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=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=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(q){p=function(a,b){var c=0,d=b||[];if(e.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var f=a.length;c<f;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){if(a===b){g=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return s(a,b);if(!h)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 s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=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}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},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)&&(l.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:[]}},l.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&&(l.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")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[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}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.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 k(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;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};f.find=k,f.expr=k.selectors,f.expr[":"]=f.expr.filters,f.unique=k.uniqueSort,f.text=k.getText,f.isXMLDoc=k.isXML,f.contains=k.contains}();var N=/Until$/,O=/^(?:parents|prevUntil|prevAll)/,P=/,/,Q=/^.[^:#\[\.,]*$/,R=Array.prototype.slice,S=f.expr.match.POS,T={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(V(this,a,!1),"not",a)},filter:function(a){return this.pushStack(V(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?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,i,j={},k=1;if(g&&a.length){for(d=0,e=a.length;d<e;d++)i=a[d],j[i]||(j[i]=S.test(i)?f(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:f(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=S.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(l?l.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(U(c[0])||U(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=R.call(arguments);N.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!T[a]?f.unique(e):e,(this.length>1||P.test(d))&&O.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 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|object|embed|option|style)/i,bb=/checked\s*(?:[^=]|=\s*.checked.)/i,bc=/\/(java|ecma)script/i,bd=/^\s*<!(?:\[CDATA\[|\-\-)/,be={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,"",""]};be.optgroup=be.option,be.tbody=be.tfoot=be.colgroup=be.caption=be.thead,be.th=be.td,f.support.htmlSerialize||(be._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(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!be[(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"&&bb.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?bf(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bl)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i;b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!ba.test(a[0])&&(f.support.checkClone||!bb.test(a[0]))&&(g=!0,h=f.fragments[a[0]],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean
(a,i,e,d)),g&&(f.fragments[a[0]]=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)){bh(a,d),e=bi(a),g=bi(d);for(h=0;e[h];++h)g[h]&&bh(e[h],g[h])}if(b){bg(a,d);if(c){e=bi(a),g=bi(d);for(h=0;e[h];++h)bg(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(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=be[l]||be._default,n=m[0],o=b.createElement("div");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++)bk(k[i]);else bk(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bc.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.expando,g=f.event.special,h=f.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&f.noData[j.nodeName.toLowerCase()])continue;c=j[f.expando];if(c){b=d[c]&&d[c][e];if(b&&b.events){for(var k in b.events)g[k]?f.event.remove(j,k):f.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[f.expando]:j.removeAttribute&&j.removeAttribute(f.expando),delete d[c]}}}});var bm=/alpha\([^)]*\)/i,bn=/opacity=([^)]*)/,bo=/([A-Z]|^ms)/g,bp=/^-?\d+(?:px)?$/i,bq=/^-?\d/,br=/^([\-+])=([\-+.\de]+)/,bs={position:"absolute",visibility:"hidden",display:"block"},bt=["Left","Right"],bu=["Top","Bottom"],bv,bw,bx;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=bv(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=br.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(bv)return bv(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 by(a,b,d);f.swap(a,bs,function(){e=by(a,b,d)});return e}},set:function(a,b){if(!bp.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bn.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.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bm,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bm.test(g)?g.replace(bm,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=bv(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bw=function(a,c){var d,e,g;c=c.replace(bo,"-$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&&(bx=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bp.test(d)&&bq.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bv=bw||bx,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.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bz=/%20/g,bA=/\[\]$/,bB=/\r?\n/g,bC=/#.*$/,bD=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bE=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bF=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bG=/^(?:GET|HEAD)$/,bH=/^\/\//,bI=/\?/,bJ=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bK=/^(?:select|textarea)/i,bL=/\s+/,bM=/([?&])_=[^&]*/,bN=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bO=f.fn.load,bP={},bQ={},bR,bS,bT=["*/"]+["*"];try{bR=e.href}catch(bU){bR=c.createElement("a"),bR.href="",bR=bR.href}bS=bN.exec(bR.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bO)return bO.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(bJ,"")).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||bK.test(this.nodeName)||bE.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(bB,"\r\n")}}):{name:b.name,value:c.replace(bB,"\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?bX(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),bX(a,b);return a},ajaxSettings:{url:bR,isLocal:bF.test(bS[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","*":bT},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:bV(bP),ajaxTransport:bV(bQ),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?bZ(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=b$(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.resolveWith(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._Deferred(),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=bD.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.done,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(bC,"").replace(bH,bS[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bL),d.crossDomain==null&&(r=bN.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bS[1]&&r[2]==bS[2]&&(r[3]||(r[1]==="http:"?80:443))==(bS[3]||(bS[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bW(bP,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bG.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bI.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bM,"$1_="+x);d.url=y+(y===d.url?(bI.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]!=="*"?", "+bT+"; 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=bW(bQ,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)bY(g,a[g],c,e);return d.join("&").replace(bz,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var b_=f.now(),ca=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+b_++}}),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&&(ca.test(b.url)||e&&ca.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(ca,l),b.url===j&&(e&&(k=k.replace(ca,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 cb=a.ActiveXObject?function(){for(var a in cd)cd[a](0,1)}:!1,cc=0,cd;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ce()||cf()}:ce,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,cb&&delete cd[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=++cc,cb&&(cd||(cd={},f(a).unload(cb)),cd[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cg={},ch,ci,cj=/^(?:toggle|show|hide)$/,ck=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cl,cm=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cn;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cq("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",cr(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(cq("hide",3),a,b,c);for(var d=0,e=this.length;d<e;d++)if(this[d].style){var g=f.css(this[d],"display");g!=="none"&&!f._data(this[d],"olddisplay")&&f._data(this[d],"olddisplay",g)}for(d=0;d<e;d++)this[d].style&&(this[d].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(cq("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){var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return this[e.queue===!1?"each":"queue"](function(){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?(j=cr(this.nodeName),j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)):this.style.display="inline-block"))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)k=new f.fx(this,b,i),h=a[i],cj.test(h)?k[h==="toggle"?d?"show":"hide":h]():(l=ck.exec(h),m=k.cur(),l?(n=parseFloat(l[2]),o=l[3]||(f.cssNumber[i]?"":"px"),o!=="px"&&(f.style(this,i,(n||1)+o),m=(n||1)/k.cur()*m,f.style(this,i,m+o)),l[1]&&(n=(l[1]==="-="?-1:1)*n+m),k.custom(m,n,o)):k.custom(m,h,""));return!0})},stop:function(a,b){a&&this.queue([]),this.each(function(){var a=f.timers,c=a.length;b||f._unmark(!0,this);while(c--)a[c].elem===this&&(b&&a[c](!0),a.splice(c,1))}),b||this.dequeue();return this}}),f.each({slideDown:cq("show",1),slideUp:cq("hide",1),slideToggle:cq("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,d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue!==!1?f.dequeue(this):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,b,c){function g(a){return d.step(a)}var d=this,e=f.fx;this.startTime=cn||co(),this.start=a,this.end=b,this.unit=c||this.unit||(f.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&f.timers.push(g)&&!cl&&(cl=setInterval(e.tick,e.interval))},show:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=cn||co(),c=!0,d=this.elem,e=this.options,g,h;if(a||b>=e.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),e.animatedProperties[this.prop]=!0;for(g in e.animatedProperties)e.animatedProperties[g]!==!0&&(c=!1);if(c){e.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){d.style["overflow"+b]=e.overflow[a]}),e.hide&&f(d).hide();if(e.hide||e.show)for(var i in e.animatedProperties)f.style(d,i,e.orig[i]);e.complete.call(d)}return!1}e.duration==Infinity?this.now=b:(h=b-this.startTime,this.state=h/e.duration,this.pos=f.easing[e.animatedProperties[this.prop]](this.state,h,0,1,e.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){for(var a=f.timers,b=0;b<a.length;++b)a[b]()||a.splice(b--,1);a.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cl),cl=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.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=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 cs=/^t(?:able|d|h)$/i,ct=/^(?: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=cu(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);f.offset.initialize();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.offset.supportsFixedPosition&&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.offset.doesNotAddBorder&&(!f.offset.doesAddBorderForTableAndCells||!cs.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.offset.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.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={initialize:function(){var a=c.body,b=c.createElement("div"),d,e,g,h,i=parseFloat(f.css(a,"marginTop"))||0,j="<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>";f.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),d=b.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,this.doesNotAddBorder=e.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,e.style.position="fixed",e.style.top="20px",this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),f.offset.initialize=f.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.offset.initialize(),f.offset.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=ct.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&&!ct.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=cu(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=cu(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")):null},f.fn["outer"+c]=function(a){var b=this[0];return b&&b.style?parseFloat(f.css(b,d,a?"margin":"border")):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.isNaN(j)?i:j}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window); |
src/scenes/firstSwiper.js | Seeingu/borrow-book | /*
首次进入时加载的Swiper
*/
import React, { Component } from 'react';
import {
Text,
View,
Image,
StatusBar,
TouchableOpacity,
} from 'react-native';
import Swiper from 'react-native-swiper';
import ViewPage from '../components/view';
import { width } from '../utils/DimensionUtil';
const styles = {
wrapper: {
},
slide: {
flex: 1,
justifyContent: 'center',
},
image: {
width,
flex: 1,
},
};
export default class extends Component {
componentDidMount() {
StatusBar.setHidden(true);
}
componentWillUnmount() {
}
render() {
return (
<View>
<Swiper
style={styles.wrapper}
showsButtons
loop={false}
>
<View style={styles.slide}>
<Image style={styles.image} resizeMode={'cover'} source={require('../assets/images/cover1.webp')} />
</View>
<View style={styles.slide}>
<Image style={styles.image} source={require('../assets/images/cover2.webp')} />
</View>
<View style={styles.slide}>
<Image style={styles.image} source={require('../assets/images/cover3.webp')} />
</View>
<View style={styles.slide}>
<Image style={styles.image} source={require('../assets/images/cover4.webp')} />
<TouchableOpacity
style={{ position: 'absolute', bottom: 30, right: 10 }}
onPress={() => this.props.router.push(ViewPage.login())}
>
<Text style={{ fontSize: 20 }}>进入</Text>
</TouchableOpacity>
</View>
</Swiper>
</View>
);
}
}
|
ajax/libs/babel-core/4.4.1/browser.min.js | sufuf3/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;"undefined"!=typeof window?n=window:"undefined"!=typeof global?n=global:"undefined"!=typeof self&&(n=self),n.babel=e()}}(function(){var e,n,l;return function t(e,n,l){function r(o,u){if(!n[o]){if(!e[o]){var s="function"==typeof require&&require;if(!u&&s)return s(o,!0);if(a)return a(o,!0);var i=new Error("Cannot find module '"+o+"'");throw i.code="MODULE_NOT_FOUND",i}var c=n[o]={exports:{}};e[o][0].call(c.exports,function(n){var l=e[o][1][n];return r(l?l:n)},c,c.exports,t,e,n,l)}return n[o].exports}for(var a="function"==typeof require&&require,o=0;o<l.length;o++)r(l[o]);return r}({1:[function(e,n){(function(l){"use strict";var t=n.exports=e("../transformation");t.version=e("../../../package").version,t.transform=t,t.run=function(e,n){return n=n||{},n.sourceMap="inline",new Function(t(e,n).code)()},t.load=function(e,n,r,a){r=r||{},r.filename=r.filename||e;var o=l.ActiveXObject?new l.ActiveXObject("Microsoft.XMLHTTP"):new l.XMLHttpRequest;o.open("GET",e,!0),"overrideMimeType"in o&&o.overrideMimeType("text/plain"),o.onreadystatechange=function(){if(4===o.readyState){var l=o.status;if(0!==l&&200!==l)throw new Error("Could not load "+e);var u=[o.responseText,r];a||t.run.apply(t,u),n&&n(u)}},o.send(null)};var r=function(){for(var e=[],n=["text/ecmascript-6","text/6to5","text/babel","module"],r=0,a=function(){var n=e[r];n instanceof Array&&(t.run.apply(t,n),r++,a())},o=function(n,l){var r={};n.src?t.load(n.src,function(n){e[l]=n,a()},r,!0):(r.filename="embedded",e[l]=[n.innerHTML,r])},u=l.document.getElementsByTagName("script"),s=0;s<u.length;++s){var i=u[s];n.indexOf(i.type)>=0&&e.push(i)}for(s in e)o(e[s],s);a()};l.addEventListener?l.addEventListener("DOMContentLoaded",r,!1):l.attachEvent&&l.attachEvent("onload",r)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../../package":317,"../transformation":40}],2:[function(e,n){"use strict";function l(e,n){this.position=e,this._indent=n.indent.base,this.format=n,this.buf=""}n.exports=l;var t=e("repeating"),r=e("trim-right"),a=e("lodash/lang/isBoolean"),o=e("lodash/collection/includes"),u=e("lodash/lang/isNumber");l.prototype.get=function(){return r(this.buf)},l.prototype.getIndent=function(){return this.format.compact||this.format.concise?"":t(this.format.indent.style,this._indent)},l.prototype.indentSize=function(){return this.getIndent().length},l.prototype.indent=function(){this._indent++},l.prototype.dedent=function(){this._indent--},l.prototype.semicolon=function(){this.push(";")},l.prototype.ensureSemicolon=function(){this.isLast(";")||this.semicolon()},l.prototype.rightBrace=function(){this.newline(!0),this.push("}")},l.prototype.keyword=function(e){this.push(e),this.space()},l.prototype.space=function(){this.format.compact||!this.buf||this.isLast(" ")||this.isLast("\n")||this.push(" ")},l.prototype.removeLast=function(e){this.format.compact||this.isLast(e)&&(this.buf=this.buf.substr(0,this.buf.length-1),this.position.unshift(e))},l.prototype.newline=function(e,n){if(!this.format.compact){if(this.format.concise)return void this.space();if(n=n||!1,u(e)){if(e=Math.min(2,e),(this.endsWith("{\n")||this.endsWith(":\n"))&&e--,0>=e)return;for(;e>0;)this._newline(n),e--}else a(e)&&(n=e),this._newline(n)}},l.prototype._newline=function(e){this.endsWith("\n\n")||(e&&this.isLast("\n")&&this.removeLast("\n"),this.removeLast(" "),this._removeSpacesAfterLastNewline(),this._push("\n"))},l.prototype._removeSpacesAfterLastNewline=function(){var e=this.buf.lastIndexOf("\n");if(-1!==e){for(var n=this.buf.length-1;n>e&&" "===this.buf[n];)n--;n===e&&(this.buf=this.buf.substring(0,n+1))}},l.prototype.push=function(e,n){if(!this.format.compact&&this._indent&&!n&&"\n"!==e){var l=this.getIndent();e=e.replace(/\n/g,"\n"+l),this.isLast("\n")&&this._push(l)}this._push(e)},l.prototype._push=function(e){this.position.push(e),this.buf+=e},l.prototype.endsWith=function(e){return this.buf.slice(-e.length)===e},l.prototype.isLast=function(e){if(this.format.compact)return!1;var n=this.buf,l=n[n.length-1];return Array.isArray(e)?o(e,l):e===l}},{"lodash/collection/includes":196,"lodash/lang/isBoolean":264,"lodash/lang/isNumber":268,repeating:300,"trim-right":316}],3:[function(e,n,l){"use strict";l.File=function(e,n){n(e.program)},l.Program=function(e,n){n.sequence(e.body)},l.BlockStatement=function(e,n){0===e.body.length?this.push("{}"):(this.push("{"),this.newline(),n.sequence(e.body,{indent:!0}),this.removeLast("\n"),this.rightBrace())}},{}],4:[function(e,n,l){"use strict";l.ClassExpression=l.ClassDeclaration=function(e,n){this.push("class"),e.id&&(this.space(),n(e.id)),e.superClass&&(this.push(" extends "),n(e.superClass)),this.space(),n(e.body)},l.ClassBody=function(e,n){0===e.body.length?this.push("{}"):(this.push("{"),this.newline(),this.indent(),n.sequence(e.body),this.dedent(),this.rightBrace())},l.MethodDefinition=function(e,n){e.static&&this.push("static "),this._method(e,n)}},{}],5:[function(e,n,l){"use strict";l.ComprehensionBlock=function(e,n){this.keyword("for"),this.push("("),n(e.left),this.push(" of "),n(e.right),this.push(")")},l.ComprehensionExpression=function(e,n){this.push(e.generator?"(":"["),n.join(e.blocks,{separator:" "}),this.space(),e.filter&&(this.keyword("if"),this.push("("),n(e.filter),this.push(")"),this.space()),n(e.body),this.push(e.generator?")":"]")}},{}],6:[function(e,n,l){"use strict";var t=e("is-integer"),r=e("lodash/lang/isNumber"),a=e("../../types");l.UnaryExpression=function(e,n){var l=/[a-z]$/.test(e.operator),t=e.argument;(a.isUpdateExpression(t)||a.isUnaryExpression(t))&&(l=!0),a.isUnaryExpression(t)&&"!"===t.operator&&(l=!1),this.push(e.operator),l&&this.push(" "),n(e.argument)},l.UpdateExpression=function(e,n){e.prefix?(this.push(e.operator),n(e.argument)):(n(e.argument),this.push(e.operator))},l.ConditionalExpression=function(e,n){n(e.test),this.space(),this.push("?"),this.space(),n(e.consequent),this.space(),this.push(":"),this.space(),n(e.alternate)},l.NewExpression=function(e,n){this.push("new "),n(e.callee),this.push("("),n.list(e.arguments),this.push(")")},l.SequenceExpression=function(e,n){n.list(e.expressions)},l.ThisExpression=function(){this.push("this")},l.CallExpression=function(e,n){n(e.callee),this.push("(");var l=",";e._prettyCall?(l+="\n",this.newline(),this.indent()):l+=" ",n.list(e.arguments,{separator:l}),e._prettyCall&&(this.newline(),this.dedent()),this.push(")")};var o=function(e){return function(n,l){this.push(e),(n.delegate||n.all)&&this.push("*"),n.argument&&(this.space(),l(n.argument))}};l.YieldExpression=o("yield"),l.AwaitExpression=o("await"),l.EmptyStatement=function(){this.semicolon()},l.ExpressionStatement=function(e,n){n(e.expression),this.semicolon()},l.BinaryExpression=l.LogicalExpression=l.AssignmentPattern=l.AssignmentExpression=function(e,n){n(e.left),this.push(" "),this.push(e.operator),this.push(" "),n(e.right)};var u=/e/i;l.MemberExpression=function(e,n){var l=e.object;if(n(l),!e.computed&&a.isMemberExpression(e.property))throw new TypeError("Got a MemberExpression for MemberExpression property");var o=e.computed;a.isLiteral(e.property)&&r(e.property.value)&&(o=!0),o?(this.push("["),n(e.property),this.push("]")):(a.isLiteral(l)&&t(l.value)&&!u.test(l.value.toString())&&this.push("."),this.push("."),n(e.property))}},{"../../types":117,"is-integer":182,"lodash/lang/isNumber":268}],7:[function(e,n,l){"use strict";l.AnyTypeAnnotation=l.ArrayTypeAnnotation=l.BooleanTypeAnnotation=l.ClassProperty=l.DeclareClass=l.DeclareFunction=l.DeclareModule=l.DeclareVariable=l.FunctionTypeAnnotation=l.FunctionTypeParam=l.GenericTypeAnnotation=l.InterfaceExtends=l.InterfaceDeclaration=l.IntersectionTypeAnnotation=l.NullableTypeAnnotation=l.NumberTypeAnnotation=l.StringLiteralTypeAnnotation=l.StringTypeAnnotation=l.TupleTypeAnnotation=l.TypeofTypeAnnotation=l.TypeAlias=l.TypeAnnotation=l.TypeParameterDeclaration=l.TypeParameterInstantiation=l.ObjectTypeAnnotation=l.ObjectTypeCallProperty=l.ObjectTypeIndexer=l.ObjectTypeProperty=l.QualifiedTypeIdentifier=l.UnionTypeAnnotation=l.TypeCastExpression=l.VoidTypeAnnotation=function(){}},{}],8:[function(e,n,l){"use strict";var t=e("../../types"),r=e("lodash/collection/each");l.JSXAttribute=function(e,n){n(e.name),e.value&&(this.push("="),n(e.value))},l.JSXIdentifier=function(e){this.push(e.name)},l.JSXNamespacedName=function(e,n){n(e.namespace),this.push(":"),n(e.name)},l.JSXMemberExpression=function(e,n){n(e.object),this.push("."),n(e.property)},l.JSXSpreadAttribute=function(e,n){this.push("{..."),n(e.argument),this.push("}")},l.JSXExpressionContainer=function(e,n){this.push("{"),n(e.expression),this.push("}")},l.JSXElement=function(e,n){var l=this,a=e.openingElement;n(a),a.selfClosing||(this.indent(),r(e.children,function(e){t.isLiteral(e)?l.push(e.value):n(e)}),this.dedent(),n(e.closingElement))},l.JSXOpeningElement=function(e,n){this.push("<"),n(e.name),e.attributes.length>0&&(this.push(" "),n.join(e.attributes,{separator:" "})),this.push(e.selfClosing?" />":">")},l.JSXClosingElement=function(e,n){this.push("</"),n(e.name),this.push(">")},l.JSXEmptyExpression=function(){}},{"../../types":117,"lodash/collection/each":193}],9:[function(e,n,l){"use strict";var t=e("../../types");l._params=function(e,n){this.push("("),n.list(e.params),this.push(")")},l._method=function(e,n){var l=e.value,t=e.kind,r=e.key;t&&"init"!==t?this.push(t+" "):l.generator&&this.push("*"),l.async&&this.push("async "),e.computed?(this.push("["),n(r),this.push("]")):n(r),this._params(l,n),this.push(" "),n(l.body)},l.FunctionDeclaration=l.FunctionExpression=function(e,n){e.async&&this.push("async "),this.push("function"),e.generator&&this.push("*"),e.id?(this.push(" "),n(e.id)):this.space(),this._params(e,n),this.space(),n(e.body)},l.ArrowFunctionExpression=function(e,n){e.async&&this.push("async "),1===e.params.length&&t.isIdentifier(e.params[0])?n(e.params[0]):this._params(e,n),this.push(" => "),n(e.body)}},{"../../types":117}],10:[function(e,n,l){"use strict";var t=e("../../types"),r=e("lodash/collection/each");l.ImportSpecifier=function(e,n){return t.isSpecifierDefault(e)?void n(t.getSpecifierName(e)):l.ExportSpecifier.apply(this,arguments)},l.ExportSpecifier=function(e,n){n(e.id),e.name&&(this.push(" as "),n(e.name))},l.ExportBatchSpecifier=function(){this.push("*")},l.ExportDeclaration=function(e,n){this.push("export ");var l=e.specifiers;if(e.default&&this.push("default "),e.declaration){if(n(e.declaration),t.isStatement(e.declaration))return}else 1===l.length&&t.isExportBatchSpecifier(l[0])?n(l[0]):(this.push("{"),l.length&&(this.space(),n.join(l,{separator:", "}),this.space()),this.push("}")),e.source&&(this.push(" from "),n(e.source));this.ensureSemicolon()},l.ImportDeclaration=function(e,n){var l=this;this.push("import "),e.isType&&this.push("type ");var a=e.specifiers;if(a&&a.length){var o=!1;r(e.specifiers,function(e,r){+r>0&&l.push(", ");var a=t.isSpecifierDefault(e);a||"ImportBatchSpecifier"===e.type||o||(o=!0,l.push("{ ")),n(e)}),o&&this.push(" }"),this.push(" from ")}n(e.source),this.semicolon()},l.ImportBatchSpecifier=function(e,n){this.push("* as "),n(e.name)}},{"../../types":117,"lodash/collection/each":193}],11:[function(e,n,l){"use strict";var t=e("lodash/collection/each");t(["BindMemberExpression","BindFunctionExpression"],function(e){l[e]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(e))}})},{"lodash/collection/each":193}],12:[function(e,n,l){"use strict";var t=e("repeating"),r=e("../../types");l.WithStatement=function(e,n){this.keyword("with"),this.push("("),n(e.object),this.push(")"),n.block(e.body)},l.IfStatement=function(e,n){this.keyword("if"),this.push("("),n(e.test),this.push(")"),this.space(),n.indentOnComments(e.consequent),e.alternate&&(this.isLast("}")&&this.space(),this.push("else "),n.indentOnComments(e.alternate))},l.ForStatement=function(e,n){this.keyword("for"),this.push("("),n(e.init),this.push(";"),e.test&&(this.push(" "),n(e.test)),this.push(";"),e.update&&(this.push(" "),n(e.update)),this.push(")"),n.block(e.body)},l.WhileStatement=function(e,n){this.keyword("while"),this.push("("),n(e.test),this.push(")"),n.block(e.body)};var a=function(e){return function(n,l){this.keyword("for"),this.push("("),l(n.left),this.push(" "+e+" "),l(n.right),this.push(")"),l.block(n.body)}};l.ForInStatement=a("in"),l.ForOfStatement=a("of"),l.DoWhileStatement=function(e,n){this.keyword("do"),n(e.body),this.space(),this.keyword("while"),this.push("("),n(e.test),this.push(");")};var o=function(e,n){return function(l,t){this.push(e);var r=l[n||"label"];r&&(this.push(" "),t(r)),this.semicolon()}};l.ContinueStatement=o("continue"),l.ReturnStatement=o("return","argument"),l.BreakStatement=o("break"),l.LabeledStatement=function(e,n){n(e.label),this.push(": "),n(e.body)},l.TryStatement=function(e,n){this.keyword("try"),n(e.block),this.space(),n(e.handlers?e.handlers[0]:e.handler),e.finalizer&&(this.space(),this.push("finally "),n(e.finalizer))},l.CatchClause=function(e,n){this.keyword("catch"),this.push("("),n(e.param),this.push(") "),n(e.body)},l.ThrowStatement=function(e,n){this.push("throw "),n(e.argument),this.semicolon()},l.SwitchStatement=function(e,n){this.keyword("switch"),this.push("("),n(e.discriminant),this.push(")"),this.space(),this.push("{"),n.sequence(e.cases,{indent:!0,addNewlines:function(n,l){return n||e.cases[e.cases.length-1]!==l?void 0:-1}}),this.push("}")},l.SwitchCase=function(e,n){e.test?(this.push("case "),n(e.test),this.push(":")):this.push("default:"),e.consequent.length&&(this.newline(),n.sequence(e.consequent,{indent:!0}))},l.DebuggerStatement=function(){this.push("debugger;")},l.VariableDeclaration=function(e,n,l){this.push(e.kind+" ");var a=!1;if(!r.isFor(l))for(var o=0;o<e.declarations.length;o++)e.declarations[o].init&&(a=!0);var u=",";u+=!this.format.compact&&a?"\n"+t(" ",e.kind.length+1):" ",n.list(e.declarations,{separator:u}),r.isFor(l)||this.semicolon()},l.PrivateDeclaration=function(e,n){this.push("private "),n.join(e.declarations,{separator:", "}),this.semicolon()},l.VariableDeclarator=function(e,n){e.init?(n(e.id),this.space(),this.push("="),this.space(),n(e.init)):n(e.id)}},{"../../types":117,repeating:300}],13:[function(e,n,l){"use strict";var t=e("lodash/collection/each");l.TaggedTemplateExpression=function(e,n){n(e.tag),n(e.quasi)},l.TemplateElement=function(e){this._push(e.value.raw)},l.TemplateLiteral=function(e,n){this.push("`");var l=e.quasis,r=this,a=l.length;t(l,function(l,t){n(l),a>t+1&&(r.push("${ "),n(e.expressions[t]),r.push(" }"))}),this._push("`")}},{"lodash/collection/each":193}],14:[function(e,n,l){"use strict";var t=e("lodash/collection/each");l.Identifier=function(e){this.push(e.name)},l.RestElement=l.SpreadElement=l.SpreadProperty=function(e,n){this.push("..."),n(e.argument)},l.VirtualPropertyExpression=function(e,n){n(e.object),this.push("::"),n(e.property)},l.ObjectExpression=l.ObjectPattern=function(e,n){var l=e.properties;l.length?(this.push("{"),this.space(),n.list(l,{indent:!0}),this.space(),this.push("}")):this.push("{}")},l.Property=function(e,n){if(e.method||"get"===e.kind||"set"===e.kind)this._method(e,n);else{if(e.computed)this.push("["),n(e.key),this.push("]");else if(n(e.key),e.shorthand)return;this.push(":"),this.space(),n(e.value)}},l.ArrayExpression=l.ArrayPattern=function(e,n){var l=e.elements,r=this,a=l.length;this.push("["),t(l,function(e,l){e?(l>0&&r.push(" "),n(e),a-1>l&&r.push(",")):r.push(",")}),this.push("]")},l.Literal=function(e){var n=e.value,l=typeof n;"string"===l?(n=JSON.stringify(n),n=n.replace(/[\u000A\u000D\u2028\u2029]/g,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}),this.push(n)):"number"===l?this.push(n+""):"boolean"===l?this.push(n?"true":"false"):e.regex?this.push("/"+e.regex.pattern+"/"+e.regex.flags):null===n&&this.push("null")}},{"lodash/collection/each":193}],15:[function(e,n){"use strict";function l(e,n,t){n=n||{},this.comments=e.comments||[],this.tokens=e.tokens||[],this.format=l.normalizeOptions(t,n),this.opts=n,this.ast=e,this.whitespace=new r(this.tokens,this.comments,this.format),this.position=new u,this.map=new o(this.position,n,t),this.buffer=new i(this.position,this.format)}n.exports=function(e,n,t){var r=new l(e,n,t);return r.generate()},n.exports.CodeGenerator=l;var t=e("detect-indent"),r=e("./whitespace"),a=e("repeating"),o=e("./source-map"),u=e("./position"),s=e("../messages"),i=e("./buffer"),c=e("lodash/object/extend"),d=e("lodash/collection/each"),p=e("./node"),f=e("../types");d(i.prototype,function(e,n){l.prototype[n]=function(){return e.apply(this.buffer,arguments)}}),l.normalizeOptions=function(e,n){var l=" ";if(e){var r=t(e).indent;r&&" "!==r&&(l=r)}var a={comments:null==n.comments||n.comments,compact:n.compact,indent:{adjustMultilineComment:!0,style:l,base:0}};return"auto"===a.compact&&(a.compact=e.length>1e5,a.compact&&console.error(s.get("codeGeneratorDeopt",n.filename,"100KB"))),a},l.generators={templateLiterals:e("./generators/template-literals"),comprehensions:e("./generators/comprehensions"),expressions:e("./generators/expressions"),statements:e("./generators/statements"),playground:e("./generators/playground"),classes:e("./generators/classes"),methods:e("./generators/methods"),modules:e("./generators/modules"),types:e("./generators/types"),flow:e("./generators/flow"),base:e("./generators/base"),jsx:e("./generators/jsx")},d(l.generators,function(e){c(l.prototype,e)}),l.prototype.generate=function(){var e=this.ast;this.print(e);var n=[];return d(e.comments,function(e){e._displayed||n.push(e)}),this._printComments(n),{map:this.map.get(),code:this.buffer.get()}},l.prototype.buildPrint=function(e){var n=this,l=function(l,t){return n.print(l,e,t)};return l.sequence=function(e,t){return t=t||{},t.statement=!0,n.printJoin(l,e,t)},l.join=function(e,t){return n.printJoin(l,e,t)},l.list=function(e,n){n=n||{},n.separator=n.separator||", ",l.join(e,n)},l.block=function(e){return n.printBlock(l,e)},l.indentOnComments=function(e){return n.printAndIndentOnComments(l,e)},l},l.prototype.print=function(e,n,l){if(!e)return"";n&&n._compact&&(e._compact=!0);var t=this.format.concise;e._compact&&(this.format.concise=!0);var r=this;l=l||{};var a=function(t){if(l.statement||p.isUserWhitespacable(e,n)){var a=0;if(null==e.start||e._ignoreUserWhitespace){t||a++,l.addNewlines&&(a+=l.addNewlines(t,e)||0);var o=p.needsWhitespaceAfter;t&&(o=p.needsWhitespaceBefore),o(e,n)&&a++,r.buffer.buf||(a=0)}else a=t?r.whitespace.getNewlinesBefore(e):r.whitespace.getNewlinesAfter(e);r.newline(a)}};if(!this[e.type])throw new ReferenceError("unknown node of type "+JSON.stringify(e.type)+" with constructor "+JSON.stringify(e&&e.constructor.name));var o=p.needsParensNoLineTerminator(e,n),u=o||p.needsParens(e,n);u&&this.push("("),o&&this.indent(),this.printLeadingComments(e,n),a(!0),l.before&&l.before(),this.map.mark(e,"start"),this[e.type](e,this.buildPrint(e),n),o&&(this.newline(),this.dedent()),u&&this.push(")"),this.map.mark(e,"end"),l.after&&l.after(),a(!1),this.printTrailingComments(e,n),this.format.concise=t},l.prototype.printJoin=function(e,n,l){if(n&&n.length){l=l||{};var t=this,r=n.length;l.indent&&t.indent(),d(n,function(n,a){e(n,{statement:l.statement,addNewlines:l.addNewlines,after:function(){l.iterator&&l.iterator(n,a),l.separator&&r-1>a&&t.push(l.separator)}})}),l.indent&&t.dedent()}},l.prototype.printAndIndentOnComments=function(e,n){var l=!!n.leadingComments;l&&this.indent(),e(n),l&&this.dedent()},l.prototype.printBlock=function(e,n){f.isEmptyStatement(n)?this.semicolon():(this.push(" "),e(n))},l.prototype.generateComment=function(e){var n=e.value;return n="Line"===e.type?"//"+n:"/*"+n+"*/"},l.prototype.printTrailingComments=function(e,n){this._printComments(this.getComments("trailingComments",e,n))},l.prototype.printLeadingComments=function(e,n){this._printComments(this.getComments("leadingComments",e,n))},l.prototype.getComments=function(e,n,l){if(f.isExpressionStatement(l))return[];var t=[],r=[n],a=this;return f.isExpressionStatement(n)&&r.push(n.argument),d(r,function(n){t=t.concat(a._getComments(e,n))}),t},l.prototype._getComments=function(e,n){return n&&n[e]||[]},l.prototype._printComments=function(e){if(!this.format.compact&&this.format.comments&&e&&e.length){var n=this;d(e,function(e){var l=!1;if(d(n.ast.comments,function(n){return n.start===e.start?(n._displayed&&(l=!0),n._displayed=!0,!1):void 0}),!l){n.newline(n.whitespace.getNewlinesBefore(e));var t=n.position.column,r=n.generateComment(e);if(t&&!n.isLast(["\n"," ","[","{"])&&(n._push(" "),t++),"Block"===e.type&&n.format.indent.adjustMultilineComment){var o=e.loc.start.column;if(o){var u=new RegExp("\\n\\s{1,"+o+"}","g");r=r.replace(u,"\n")}var s=Math.max(n.indentSize(),t);r=r.replace(/\n/g,"\n"+a(" ",s))}0===t&&(r=n.getIndent()+r),n._push(r),n.newline(n.whitespace.getNewlinesAfter(e))}})}}},{"../messages":27,"../types":117,"./buffer":2,"./generators/base":3,"./generators/classes":4,"./generators/comprehensions":5,"./generators/expressions":6,"./generators/flow":7,"./generators/jsx":8,"./generators/methods":9,"./generators/modules":10,"./generators/playground":11,"./generators/statements":12,"./generators/template-literals":13,"./generators/types":14,"./node":16,"./position":19,"./source-map":20,"./whitespace":21,"detect-indent":174,"lodash/collection/each":193,"lodash/object/extend":275,repeating:300}],16:[function(e,n){"use strict";function l(e,n){this.parent=n,this.node=e}n.exports=l;var t=e("./whitespace"),r=e("./parentheses"),a=e("lodash/collection/each"),o=e("lodash/collection/some"),u=e("../../types"),s=function(e,n,l){if(e){for(var t,r=Object.keys(e),a=0;a<r.length;a++){var o=r[a];if(u.is(o,n)){var s=e[o];if(t=s(n,l),null!=t)break}}return t}};l.isUserWhitespacable=function(e){return u.isUserWhitespacable(e)},l.needsWhitespace=function(e,n,r){if(!e)return 0;u.isExpressionStatement(e)&&(e=e.expression);var a=s(t.nodes,e,n);if(!a){var o=s(t.list,e,n);if(o)for(var i=0;i<o.length&&!(a=l.needsWhitespace(o[i],e,r));i++);}return a&&a[r]||0},l.needsWhitespaceBefore=function(e,n){return l.needsWhitespace(e,n,"before")},l.needsWhitespaceAfter=function(e,n){return l.needsWhitespace(e,n,"after")},l.needsParens=function(e,n){if(!n)return!1;if(u.isNewExpression(n)&&n.callee===e){if(u.isCallExpression(e))return!0;var l=o(e,function(e){return u.isCallExpression(e)});if(l)return!0}return s(r,e,n)},l.needsParensNoLineTerminator=function(e,n){return n&&e.leadingComments&&e.leadingComments.length?u.isYieldExpression(n)||u.isAwaitExpression(n)?!0:u.isContinueStatement(n)||u.isBreakStatement(n)||u.isReturnStatement(n)||u.isThrowStatement(n)?!0:!1:!1},a(l,function(e,n){l.prototype[n]=function(){var e=new Array(arguments.length+2);e[0]=this.node,e[1]=this.parent;for(var t=0;t<e.length;t++)e[t+2]=arguments[t];return l[n].apply(null,e)}})},{"../../types":117,"./parentheses":17,"./whitespace":18,"lodash/collection/each":193,"lodash/collection/some":199}],17:[function(e,n,l){"use strict";var t=e("../../types"),r=e("lodash/collection/each"),a={};r([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(e,n){r(e,function(e){a[e]=n})}),l.UpdateExpression=function(e,n){return t.isMemberExpression(n)&&n.object===e?!0:void 0},l.ObjectExpression=function(e,n){return t.isExpressionStatement(n)?!0:t.isMemberExpression(n)&&n.object===e?!0:!1},l.Binary=function(e,n){if((t.isCallExpression(n)||t.isNewExpression(n))&&n.callee===e)return!0;if(t.isUnaryLike(n))return!0;if(t.isMemberExpression(n)&&n.object===e)return!0;if(t.isBinary(n)){var l=n.operator,r=a[l],o=e.operator,u=a[o];if(r>u)return!0;if(r===u&&n.right===e)return!0}},l.BinaryExpression=function(e,n){if("in"===e.operator){if(t.isVariableDeclarator(n))return!0;if(t.isFor(n))return!0}},l.SequenceExpression=function(e,n){return t.isForStatement(n)?!1:t.isExpressionStatement(n)&&n.expression===e?!1:!0},l.YieldExpression=function(e,n){return t.isBinary(n)||t.isUnaryLike(n)||t.isCallExpression(n)||t.isMemberExpression(n)||t.isNewExpression(n)||t.isConditionalExpression(n)||t.isYieldExpression(n)},l.ClassExpression=function(e,n){return t.isExpressionStatement(n)},l.UnaryLike=function(e,n){return t.isMemberExpression(n)&&n.object===e},l.FunctionExpression=function(e,n){return t.isExpressionStatement(n)?!0:t.isMemberExpression(n)&&n.object===e?!0:t.isCallExpression(n)&&n.callee===e?!0:void 0},l.AssignmentExpression=l.ConditionalExpression=function(e,n){return t.isUnaryLike(n)?!0:t.isBinary(n)?!0:(t.isCallExpression(n)||t.isNewExpression(n))&&n.callee===e?!0:t.isConditionalExpression(n)&&n.test===e?!0:t.isMemberExpression(n)&&n.object===e?!0:!1}},{"../../types":117,"lodash/collection/each":193}],18:[function(e,n,l){"use strict";var t=e("lodash/lang/isBoolean"),r=e("lodash/collection/each"),a=e("lodash/collection/map"),o=e("../../types"),u=function(e,n){return n=n||{},o.isMemberExpression(e)?(u(e.object,n),e.computed&&u(e.property,n)):o.isBinary(e)||o.isAssignmentExpression(e)?(u(e.left,n),u(e.right,n)):o.isCallExpression(e)?(n.hasCall=!0,u(e.callee,n)):o.isFunction(e)?n.hasFunction=!0:o.isIdentifier(e)&&(n.hasHelper=n.hasHelper||s(e.callee)),n},s=function(e){return o.isMemberExpression(e)?s(e.object)||s(e.property):o.isIdentifier(e)?"require"===e.name||"_"===e.name[0]:o.isCallExpression(e)?s(e.callee):o.isBinary(e)||o.isAssignmentExpression(e)?o.isIdentifier(e.left)&&s(e.left)||s(e.right):!1},i=function(e){return o.isLiteral(e)||o.isObjectExpression(e)||o.isArrayExpression(e)||o.isIdentifier(e)||o.isMemberExpression(e)};l.nodes={AssignmentExpression:function(e){var n=u(e.right);return n.hasCall&&n.hasHelper||n.hasFunction?{before:n.hasFunction,after:!0}:void 0},SwitchCase:function(e,n){return{before:e.consequent.length||n.cases[0]===e}},LogicalExpression:function(e){return o.isFunction(e.left)||o.isFunction(e.right)?{after:!0}:void 0},Literal:function(e){return"use strict"===e.value?{after:!0}:void 0},CallExpression:function(e){return o.isFunction(e.callee)||s(e)?{before:!0,after:!0}:void 0},VariableDeclaration:function(e){for(var n=0;n<e.declarations.length;n++){var l=e.declarations[n],t=s(l.id)&&!i(l.init);if(!t){var r=u(l.init);t=s(l.init)&&r.hasCall||r.hasFunction}if(t)return{before:!0,after:!0}}},IfStatement:function(e){return o.isBlockStatement(e.consequent)?{before:!0,after:!0}:void 0}},l.nodes.Property=l.nodes.SpreadProperty=function(e,n){return n.properties[0]===e?{before:!0}:void 0},l.list={VariableDeclaration:function(e){return a(e.declarations,"init")},ArrayExpression:function(e){return e.elements},ObjectExpression:function(e){return e.properties}},r({Function:!0,Class:!0,Loop:!0,LabeledStatement:!0,SwitchStatement:!0,TryStatement:!0},function(e,n){t(e)&&(e={after:e,before:e}),r([n].concat(o.FLIPPED_ALIAS_KEYS[n]||[]),function(n){l.nodes[n]=function(){return e}})})},{"../../types":117,"lodash/collection/each":193,"lodash/collection/map":197,"lodash/lang/isBoolean":264}],19:[function(e,n){"use strict";function l(){this.line=1,this.column=0}n.exports=l,l.prototype.push=function(e){for(var n=0;n<e.length;n++)"\n"===e[n]?(this.line++,this.column=0):this.column++},l.prototype.unshift=function(e){for(var n=0;n<e.length;n++)"\n"===e[n]?this.line--:this.column--}},{}],20:[function(e,n){"use strict";function l(e,n,l){this.position=e,this.opts=n,n.sourceMap?(this.map=new t.SourceMapGenerator({file:n.sourceMapName,sourceRoot:n.sourceRoot}),this.map.setSourceContent(n.sourceFileName,l)):this.map=null}n.exports=l;var t=e("source-map"),r=e("../types");l.prototype.get=function(){var e=this.map;return e?e.toJSON():e},l.prototype.mark=function(e,n){var l=e.loc;if(l){var t=this.map;if(t&&!r.isProgram(e)&&!r.isFile(e)){var a=this.position,o={line:a.line,column:a.column},u=l[n];t.addMapping({source:this.opts.sourceFileName,generated:o,original:u})}}}},{"../types":117,"source-map":305}],21:[function(e,n){"use strict";function l(e,n,l){return e+=n,e>=l&&(e-=l),e}function t(e,n){this.tokens=r(e.concat(n),"start"),this.used={},this._lastFoundIndex=0}n.exports=t;var r=e("lodash/collection/sortBy");t.prototype.getNewlinesBefore=function(e){for(var n,t,r,a=this.tokens,o=0;o<a.length;o++){var u=l(o,this._lastFoundIndex,this.tokens.length);if(r=a[u],e.start===r.start){n=a[u-1],t=r,this._lastFoundIndex=u;break}}return this.getNewlinesBetween(n,t)},t.prototype.getNewlinesAfter=function(e){for(var n,t,r,a=this.tokens,o=0;o<a.length;o++){var u=l(o,this._lastFoundIndex,this.tokens.length);if(r=a[u],e.end===r.end){n=r,t=a[u+1],this._lastFoundIndex=u;break}}if(t&&"eof"===t.type.type)return 1;var s=this.getNewlinesBetween(n,t);return"Line"!==e.type||s?s:1},t.prototype.getNewlinesBetween=function(e,n){if(!n||!n.loc)return 0;for(var l=e?e.loc.end.line:1,t=n.loc.start.line,r=0,a=l;t>a;a++)"undefined"==typeof this.used[a]&&(this.used[a]=!0,r++);return r}},{"lodash/collection/sortBy":200}],22:[function(e,n){var l=e("repeating"),t=e("js-tokenizer"),r=e("chalk"),a={string1:"red",string2:"red",punct:["white","bold"],curly:"green",parens:["blue","bold"],square:["yellow"],name:"white",keyword:["cyan"],number:"magenta",regexp:"magenta",comment1:"grey",comment2:"grey"},o=function(e){var n=function(e,n){return n?(Array.isArray(n)?n.forEach(function(n){e=r[n](e)}):e=r[n](e),e):e};return t(e,!0).map(function(e){var l=t.type(e);return n(e,a[l])}).join("")};n.exports=function(e,n,t){t=Math.max(t,0),r.supportsColor&&(e=o(e)),e=e.split(/\r\n|[\n\r\u2028\u2029]/);var a=Math.max(n-3,0),u=Math.min(e.length,n+3),s=(u+"").length;return n||t||(a=0,u=e.length),"\n"+e.slice(a,u).map(function(e,r){var o=r+a+1,u=o===n?"> ":" ",i=o+l(" ",s+1);u+=i+"| ";var c=u+e;return t&&o===n&&(c+="\n",c+=l(" ",u.length-2),c+="|"+l(" ",t)+"^"),c}).join("\n")}},{chalk:162,"js-tokenizer":185,repeating:300}],23:[function(e,n){var l=e("../types");n.exports=function(e,n,t){if(e&&"Program"===e.type)return l.file(e,n||[],t||[]);throw new Error("Not a valid ast?")}},{"../types":117}],24:[function(e,n){"use strict";n.exports=function(){return Object.create(null)}},{}],25:[function(e,n){var l=e("./normalize-ast"),t=e("estraverse"),r=e("./code-frame"),a=e("acorn-babel");n.exports=function(e,n,o){try{var u=[],s=[],i=a.parse(n,{allowImportExportEverywhere:e.allowImportExportEverywhere,allowReturnOutsideFunction:!e._anal,ecmaVersion:e.experimental?7:6,playground:e.playground,strictMode:e.strictMode,onComment:u,locations:!0,onToken:s,ranges:!0});return t.attachComments(i,u,s),i=l(i,u,s),o?o(i):i}catch(c){if(!c._babel){c._babel=!0;var d=e.filename+": "+c.message,p=c.loc;if(p){var f=r(n,p.line,p.column+1);d+=f}c.stack&&(c.stack=c.stack.replace(c.message,d)),c.message=d}throw c}}},{"./code-frame":22,"./normalize-ast":23,"acorn-babel":120,estraverse:175}],26:[function(e,n,l){"use strict";n.exports=function t(e){function n(){}return n.prototype=e,n}},{}],27:[function(e,n,l){var t=e("util");l.messages={tailCallReassignmentDeopt:"Function reference has been reassigned so it's probably be dereferenced so we can't optimise this with confidence",JSXNamespacedTags:"Namespace tags are not supported. ReactJSX is not XML.",classesIllegalBareSuper:"Illegal use of bare super",classesIllegalSuperCall:"Direct super call is illegal in non-constructor, use super.$1() instead",classesIllegalConstructorKind:"Illegal kind for constructor method",scopeDuplicateDeclaration:"Duplicate declaration $1",undeclaredVariable:"Reference to undeclared variable $1",undeclaredVariableSuggestion:"Reference to undeclared variable $1 - did you mean $2?",settersInvalidParamLength:"Setters must have exactly one parameter",noAssignmentsInForHead:"No assignments allowed in for-in/of head",expectedMemberExpressionOrIdentifier:"Expected type MemeberExpression or Identifier",invalidParentForThisNode:"We don't know how to handle this node within the current parent - please open an issue",readOnly:"$1 is read-only",modulesIllegalExportName:"Illegal export $1",unknownForHead:"Unknown node type $1 in ForStatement",didYouMean:"Did you mean $1?",evalInStrictMode:"eval is not allowed in strict mode",codeGeneratorDeopt:"Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2."},l.get=function(e){var n=l.messages[e];
if(!n)throw new ReferenceError("Unknown message `"+e+"`");for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);return t=l.parseArgs(t),n.replace(/\$(\d+)/g,function(e,n){return t[--n]})},l.parseArgs=function(e){return e.map(function(e){if(null!=e&&e.inspect)return e.inspect();try{return JSON.stringify(e)||e+""}catch(n){return t.inspect(e)}})}},{util:161}],28:[function(e){"use strict";var n=e("lodash/object/extend"),l=e("./types"),t=e("estraverse");n(t.VisitorKeys,l.VISITOR_KEYS);var r=e("ast-types"),a=r.Type.def,o=r.Type.or;a("File").bases("Node").build("program").field("program",a("Program")),a("AssignmentPattern").bases("Pattern").build("left","right").field("left",a("Pattern")).field("right",a("Expression")),a("ImportBatchSpecifier").bases("Specifier").build("name").field("name",a("Identifier")),a("RestElement").bases("Pattern").build("argument").field("argument",a("expression")),a("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",a("Expression")).field("property",o(a("Identifier"),a("Expression"))),a("PrivateDeclaration").bases("Declaration").build("declarations").field("declarations",[a("Identifier")]),a("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",a("Expression")).field("property",o(a("Identifier"),a("Expression"))).field("arguments",[a("Expression")]),a("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",a("Expression")).field("arguments",[a("Expression")]),r.finalize()},{"./types":117,"ast-types":134,estraverse:175,"lodash/object/extend":275}],29:[function(e,n){"use strict";function l(e){this.dynamicImportedNoDefault=[],this.dynamicImportIds={},this.dynamicImported=[],this.dynamicImports=[],this.dynamicData={},this.data={},this.lastStatements=[],this.opts=this.normalizeOptions(e),this.ast={},this.buildTransformers()}n.exports=l;var t=e("source-map-to-comment"),r=e("shebang-regex"),a=e("lodash/lang/isFunction"),o=e("./index"),u=e("../generation"),s=e("lodash/object/defaults"),i=e("lodash/collection/includes"),c=e("lodash/object/assign"),d=e("../helpers/parse"),p=e("../traversal/scope"),f=e("slash"),g=e("../util"),h=e("path"),m=e("lodash/collection/each"),y=e("../types");l.helpers=["inherits","defaults","prototype-properties","apply-constructor","tagged-template-literal","tagged-template-literal-loose","interop-require","to-array","to-consumable-array","sliced-to-array","object-without-properties","has-own","slice","bind","define-property","async-to-generator","interop-require-wildcard","typeof","extends","get","set","class-call-check","object-destructuring-empty","temporal-undefined","temporal-assert-defined","self-global"],l.validOptions=["filename","filenameRelative","blacklist","whitelist","loose","optional","modules","sourceMap","sourceMapName","sourceFileName","sourceRoot","moduleRoot","moduleIds","comments","reactCompat","keepModuleIdExtensions","code","ast","playground","experimental","externalHelpers","auxiliaryComment","compact","resolveModuleSource","getModuleName","format","ignore","only","extensions","accept"],l.prototype.normalizeOptions=function(e){e=c({},e);for(var n in e)if("_"!==n[0]&&l.validOptions.indexOf(n)<0)throw new ReferenceError("Unknown option: "+n);s(e,{keepModuleIdExtensions:!1,resolveModuleSource:null,externalHelpers:!1,auxilaryComment:"",experimental:!1,reactCompat:!1,playground:!1,moduleIds:!1,blacklist:[],whitelist:[],sourceMap:!1,optional:[],comments:!0,filename:"unknown",modules:"common",compact:"auto",loose:[],code:!0,ast:!0}),e.filename=f(e.filename),e.sourceRoot&&(e.sourceRoot=f(e.sourceRoot)),e.basename=h.basename(e.filename,h.extname(e.filename)),e.blacklist=g.arrayify(e.blacklist),e.whitelist=g.arrayify(e.whitelist),e.optional=g.arrayify(e.optional),e.compact=g.booleanify(e.compact),e.loose=g.arrayify(e.loose),(i(e.loose,"all")||i(e.loose,!0))&&(e.loose=Object.keys(o.transformers)),s(e,{moduleRoot:e.sourceRoot}),s(e,{sourceRoot:e.moduleRoot}),s(e,{filenameRelative:e.filename}),s(e,{sourceFileName:e.filenameRelative,sourceMapName:e.filenameRelative}),e.playground&&(e.experimental=!0),e.externalHelpers&&this.set("runtimeIdentifier",y.identifier("babelHelpers")),e.blacklist=o._ensureTransformerNames("blacklist",e.blacklist),e.whitelist=o._ensureTransformerNames("whitelist",e.whitelist),e.optional=o._ensureTransformerNames("optional",e.optional),e.loose=o._ensureTransformerNames("loose",e.loose),e.reactCompat&&(e.optional.push("reactCompat"),console.error("The reactCompat option has been moved into the optional transformer `reactCompat`"));var t=function(n){var l=o.transformerNamespaces[n];"es7"===l&&(e.experimental=!0),"playground"===l&&(e.playground=!0)};return m(e.whitelist,t),m(e.optional,t),e},l.prototype.isLoose=function(e){return i(this.opts.loose,e)},l.prototype.buildTransformers=function(){var e=this,n={},l=[],t=[];m(o.transformers,function(r,a){var o=n[a]=r.buildPass(e);o.canRun(e)&&(t.push(o),r.secondPass&&l.push(o),r.manipulateOptions&&r.manipulateOptions(e.opts,e))}),this.transformerStack=t.concat(l),this.transformers=n},l.prototype.debug=function(e){var n=this.opts.filename;e&&(n+=": "+e),g.debug(n)},l.prototype.getModuleFormatter=function(n){var l=a(n)?n:o.moduleFormatters[n];if(!l){var t=g.resolve(n);t&&(l=e(t))}if(!l)throw new ReferenceError("Unknown module formatter type "+JSON.stringify(n));return new l(this)},l.prototype.parseShebang=function(e){var n=r.exec(e);return n&&(this.shebang=n[0],e=e.replace(r,"")),e},l.prototype.set=function(e,n){return this.data[e]=n},l.prototype.setDynamic=function(e,n){this.dynamicData[e]=n},l.prototype.get=function(e){var n=this.data[e];if(n)return n;var l=this.dynamicData[e];return l?this.set(e,l()):void 0},l.prototype.addImport=function(e,n,l){n=n||e;var t=this.dynamicImportIds[n];if(!t){t=this.dynamicImportIds[n]=this.scope.generateUidIdentifier(n);var r=[y.importSpecifier(y.identifier("default"),t)],a=y.importDeclaration(r,y.literal(e));a._blockHoist=3,this.dynamicImported.push(a),l&&this.dynamicImportedNoDefault.push(a),this.moduleFormatter.importSpecifier(r[0],a,this.dynamicImports)}return t},l.prototype.isConsequenceExpressionStatement=function(e){return y.isExpressionStatement(e)&&this.lastStatements.indexOf(e)>=0},l.prototype.attachAuxiliaryComment=function(e){var n=this.opts.auxiliaryComment;return n&&(e.leadingComments=e.leadingComments||[],e.leadingComments.push({type:"Line",value:" "+n})),e},l.prototype.addHelper=function(e){if(!i(l.helpers,e))throw new ReferenceError("Unknown helper "+e);var n=this.ast.program,t=n._declarations&&n._declarations[e];if(t)return t.id;var r=this.get("runtimeIdentifier");if(r)return e=y.identifier(y.toIdentifier(e)),y.memberExpression(r,e);var a=g.template(e);a._compact=!0;var o=this.scope.generateUidIdentifier(e);return this.scope.push({key:e,id:o,init:a}),o},l.prototype.logDeopt=function(){},l.prototype.errorWithNode=function(e,n,l){l=l||SyntaxError;var t=e.loc.start,r=new l("Line "+t.line+": "+n);return r.loc=t,r},l.prototype.addCode=function(e){return e=(e||"")+"",this.code=e,this.parseShebang(e)},l.prototype.parse=function(e){var n=this;e=this.addCode(e);var l=this.opts;return l.allowImportExportEverywhere=this.isLoose("es6.modules"),l.strictMode=this.transformers.useStrict.canRun(),d(l,e,function(e){return n.transform(e),n.generate()})},l.prototype.transform=function(e){this.debug(),this.ast=e,this.lastStatements=y.getLastStatements(e.program),this.scope=new p(e.program,e,null,this);var n=this.moduleFormatter=this.getModuleFormatter(this.opts.modules);n.init&&this.transformers["es6.modules"].canRun()&&n.init(),this.checkNode(e),this.call("pre"),m(this.transformerStack,function(e){e.transform()}),this.call("post")},l.prototype.call=function(e){for(var n=this.transformerStack,l=0;l<n.length;l++){var t=n[l].transformer;t[e]&&t[e](this)}};var x={enter:function(e,n,l,t){b(t.stack,e,l)}},b=function(e,n,l){m(e,function(e){e.shouldRun||e.checkNode(n,l)})};l.prototype.checkNode=function(e,n){var l=this.transformerStack;n=n||this.scope,b(l,e,n),n.traverse(e,x,{stack:l})},l.prototype.generate=function(){var e=this.opts,n=this.ast,l={code:"",map:null,ast:null};if(e.ast&&(l.ast=n),!e.code)return l;var r=u(n,e,this.code);return l.code=r.code,l.map=r.map,this.shebang&&(l.code=this.shebang+"\n"+l.code),"inline"===e.sourceMap&&(l.code+="\n"+t(l.map),l.map=null),l}},{"../generation":15,"../helpers/parse":25,"../traversal/scope":114,"../types":117,"../util":119,"./index":40,"lodash/collection/each":193,"lodash/collection/includes":196,"lodash/lang/isFunction":266,"lodash/object/assign":273,"lodash/object/defaults":274,path:144,"shebang-regex":302,slash:303,"source-map-to-comment":304}],30:[function(e,n){"use strict";var l=e("./explode-assignable-expression"),t=e("../../types");n.exports=function(e,n){var r=function(e){return e.operator===n.operator+"="},a=function(e,n){return t.assignmentExpression("=",e,n)};e.ExpressionStatement=function(e,o,u,s){if(!s.isConsequenceExpressionStatement(e)){var i=e.expression;if(r(i)){var c=[],d=l(i.left,c,s,u,!0);return c.push(t.expressionStatement(a(d.ref,n.build(d.uid,i.right)))),c}}},e.AssignmentExpression=function(e,o,u,s){if(r(e)){var i=[],c=l(e.left,i,s,u);return i.push(a(c.ref,n.build(c.uid,e.right))),t.toSequenceExpression(i,u)}},e.BinaryExpression=function(e){return e.operator===n.operator?n.build(e.left,e.right):void 0}}},{"../../types":117,"./explode-assignable-expression":35}],31:[function(e,n){"use strict";var l=e("../../types");n.exports=function t(e,n){var r=e.blocks.shift();if(r){var a=t(e,n);return a||(a=n(),e.filter&&(a=l.ifStatement(e.filter,l.blockStatement([a])))),l.forOfStatement(l.variableDeclaration("let",[l.variableDeclarator(r.left)]),r.right,l.blockStatement([a]))}}},{"../../types":117}],32:[function(e,n){"use strict";var l=e("./explode-assignable-expression"),t=e("../../types");n.exports=function(e,n){var r=function(e,n){return t.assignmentExpression("=",e,n)};e.ExpressionStatement=function(e,a,o,u){if(!u.isConsequenceExpressionStatement(e)){var s=e.expression;if(n.is(s,u)){var i=[],c=l(s.left,i,u,o);return i.push(t.ifStatement(n.build(c.uid,u),t.expressionStatement(r(c.ref,s.right)))),i}}},e.AssignmentExpression=function(e,a,o,u){if(n.is(e,u)){var s=[],i=l(e.left,s,u,o);return s.push(t.logicalExpression("&&",n.build(i.uid,u),r(i.ref,e.right))),s.push(i.ref),t.toSequenceExpression(s,o)}}}},{"../../types":117,"./explode-assignable-expression":35}],33:[function(e,n){"use strict";var l=e("lodash/lang/isString"),t=e("../../messages"),r=e("esutils"),a=e("./react"),o=e("../../types");n.exports=function(e,n){e.check=function(e){return o.isJSX(e)?!0:a.isCreateClass(e)?!0:!1},e.JSXIdentifier=function(e,n){return"this"===e.name&&o.isReferenced(e,n)?o.thisExpression():r.keyword.isIdentifierName(e.name)?void(e.type="Identifier"):o.literal(e.name)},e.JSXNamespacedName=function(e,n,l,r){throw r.errorWithNode(e,t.get("JSXNamespacedTags"))},e.JSXMemberExpression={exit:function(e){e.computed=o.isLiteral(e.property),e.type="MemberExpression"}},e.JSXExpressionContainer=function(e){return e.expression},e.JSXAttribute={exit:function(e){var n=e.value||o.literal(!0);return o.isLiteral(n)&&l(n.value)&&(n.value=n.value.replace(/\n\s+/g," ")),o.inherits(o.property("init",e.name,n),e)}},e.JSXOpeningElement={exit:function(e,l,t,r){var a,s=e.name,i=[];o.isIdentifier(s)?a=s.name:o.isLiteral(s)&&(a=s.value);var c={tagExpr:s,tagName:a,args:i};n.pre&&n.pre(c,r);var d=e.attributes;return d=d.length?u(d,r):o.literal(null),i.push(d),n.post&&n.post(c,r),c.call||o.callExpression(c.callee,i)}};var u=function(e,n){for(var l=[],t=[],r=function(){l.length&&(t.push(o.objectExpression(l)),l=[])};e.length;){var a=e.shift();o.isJSXSpreadAttribute(a)?(r(),t.push(a.argument)):l.push(a)}return r(),1===t.length?e=t[0]:(o.isObjectExpression(t[0])||t.unshift(o.objectExpression([])),e=o.callExpression(n.addHelper("extends"),t)),e};e.JSXElement={exit:function(e){for(var n=e.openingElement,l=0;l<e.children.length;l++){var t=e.children[l];o.isLiteral(t)&&"string"==typeof t.value?c(t,n.arguments):o.isJSXEmptyExpression(t)||n.arguments.push(t)}return n.arguments=i(n.arguments),n.arguments.length>=3&&(n._prettyCall=!0),o.inherits(n,e)}};var s=function(e){return o.isLiteral(e)&&l(e.value)},i=function(e){for(var n,l=[],t=0;t<e.length;t++){var r=e[t];s(r)&&s(n)?n.value+=r.value:(n=r,l.push(r))}return l},c=function(e,n){var l,t=e.value.split(/\r\n|\n|\r/),r=0;for(l=0;l<t.length;l++)t[l].match(/[^ \t]/)&&(r=l);for(l=0;l<t.length;l++){var a=t[l],u=0===l,s=l===t.length-1,i=l===r,c=a.replace(/\t/g," ");u||(c=c.replace(/^[ ]+/,"")),s||(c=c.replace(/[ ]+$/,"")),c&&(i||(c+=" "),n.push(o.literal(c)))}},d=function(e,n){for(var l=n.arguments[0].properties,t=!0,r=0;r<l.length;r++){var a=l[r];if(o.isIdentifier(a.key,{name:"displayName"})){t=!1;break}}t&&l.unshift(o.property("init",o.identifier("displayName"),o.literal(e)))};e.ExportDeclaration=function(e,n,l,t){e.default&&a.isCreateClass(e.declaration)&&d(t.opts.basename,e.declaration)},e.AssignmentExpression=e.Property=e.VariableDeclarator=function(e){var n,l;o.isAssignmentExpression(e)?(n=e.left,l=e.right):o.isProperty(e)?(n=e.key,l=e.value):o.isVariableDeclarator(e)&&(n=e.id,l=e.init),o.isMemberExpression(n)&&(n=n.property),o.isIdentifier(n)&&a.isCreateClass(l)&&d(n.name,l)}}},{"../../messages":27,"../../types":117,"./react":37,esutils:179,"lodash/lang/isString":271}],34:[function(e,n,l){var t=e("lodash/lang/cloneDeep"),r=e("../../traversal"),a=e("lodash/lang/clone"),o=e("lodash/collection/each"),u=e("lodash/object/has"),s=e("../../types");l.push=function(e,n,l,a,o){var i;s.isIdentifier(n)?(i=n.name,a&&(i="computed:"+i)):i=s.isLiteral(n)?String(n.value):JSON.stringify(r.removeProperties(t(n)));var c;c=u(e,i)?e[i]:{},e[i]=c,c._key=n,a&&(c._computed=!0),c[l]=o},l.build=function(e){var n=s.objectExpression([]);return o(e,function(e){var l=s.objectExpression([]),t=s.property("init",e._key,l,e._computed);e.get||e.set||(e.writable=s.literal(!0)),e.enumerable===!1?delete e.enumerable:e.enumerable=s.literal(!0),e.configurable=s.literal(!0),o(e,function(e,n){if("_"!==n[0]){e=a(e);var t=e;s.isMethodDefinition(e)&&(e=e.value);var r=s.property("init",s.identifier(n),e);s.inheritsComments(r,t),s.removeComments(t),l.properties.push(r)}}),n.properties.push(t)}),n}},{"../../traversal":112,"../../types":117,"lodash/collection/each":193,"lodash/lang/clone":260,"lodash/lang/cloneDeep":261,"lodash/object/has":276}],35:[function(e,n){"use strict";var l=e("../../types"),t=function(e,n,t,r){var a;if(l.isIdentifier(e)){if(r.hasBinding(e.name))return e;a=e}else{if(!l.isMemberExpression(e))throw new Error("We can't explode this node type "+e.type);if(a=e.object,l.isIdentifier(a)&&r.hasGlobal(a.name))return a}var o=r.generateUidBasedOnNode(a);return n.push(l.variableDeclaration("var",[l.variableDeclarator(o,a)])),o},r=function(e,n,t,r){var a=e.property,o=l.toComputedKey(e,a);if(l.isLiteral(o))return o;var u=r.generateUidBasedOnNode(a);return n.push(l.variableDeclaration("var",[l.variableDeclarator(u,a)])),u};n.exports=function(e,n,a,o,u){var s;s=l.isIdentifier(e)&&u?e:t(e,n,a,o);var i,c;if(l.isIdentifier(e))i=e,c=s;else{var d=r(e,n,a,o),p=e.computed||l.isLiteral(d);c=i=l.memberExpression(s,d,p)}return{uid:c,ref:i}}},{"../../types":117}],36:[function(e,n,l){"use strict";var t=e("../../util"),r=e("../../types"),a={enter:function(e,n,l,t){if(r.isIdentifier(e,{name:t.id})&&r.isReferenced(e,n)){var a=l.getBindingIdentifier(t.id);a===t.outerDeclar&&(t.selfReference=!0,this.stop())}}};l.property=function(e,n,l){var o=r.toComputedKey(e,e.key);if(!r.isLiteral(o))return e;var u=r.toIdentifier(o.value);o=r.identifier(u);var s={id:u,selfReference:!1,outerDeclar:l.getBindingIdentifier(u)};l.traverse(e,a,s);var i=e.value;if(s.selfReference){var c="property-method-assignment-wrapper";i.generator&&(c+="-generator"),e.value=t.template(c,{FUNCTION:i,FUNCTION_ID:o,FUNCTION_KEY:l.generateUidIdentifier(u),WRAPPER_KEY:l.generateUidIdentifier(u+"Wrapper")})}else i.id=o}},{"../../types":117,"../../util":119}],37:[function(e,n,l){var t=e("../../types"),r=t.buildMatchMemberExpression("React.createClass");l.isCreateClass=function(e){if(!e||!t.isCallExpression(e))return!1;if(!r(e.callee))return!1;var n=e.arguments;if(1!==n.length)return!1;var l=n[0];return t.isObjectExpression(l)?!0:!1},l.isReactComponent=t.buildMatchMemberExpression("React.Component"),l.isCompatTag=function(e){return e&&/^[a-z]|\-/.test(e)}},{"../../types":117}],38:[function(e,n){"use strict";var l=e("../../types"),t={enter:function(e){l.isFunction(e)&&this.skip(),l.isAwaitExpression(e)&&(e.type="YieldExpression",e.all&&(e.all=!1,e.argument=l.callExpression(l.memberExpression(l.identifier("Promise"),l.identifier("all")),[e.argument])))}};n.exports=function(e,n,r){e.async=!1,e.generator=!0,r.traverse(e,t);var a=l.callExpression(n,[e]),o=e.id;if(delete e.id,l.isFunctionDeclaration(e)){var u=l.variableDeclaration("let",[l.variableDeclarator(o,a)]);return u._blockHoist=!0,u}return a}},{"../../types":117}],39:[function(e,n){"use strict";function l(e,n){this.topLevelThisReference=e.topLevelThisReference,this.methodNode=e.methodNode,this.className=e.className,this.superName=e.superName,this.isStatic=e.isStatic,this.hasSuper=!1,this.inClass=n,this.isLoose=e.isLoose,this.scope=e.scope,this.file=e.file}n.exports=l;var t=e("../../messages"),r=e("../../types");l.prototype.setSuperProperty=function(e,n,l,t){return r.callExpression(this.file.addHelper("set"),[r.callExpression(r.memberExpression(r.identifier("Object"),r.identifier("getPrototypeOf")),[this.isStatic?this.className:r.memberExpression(this.className,r.identifier("prototype"))]),l?e:r.literal(e.name),n,t])},l.prototype.getSuperProperty=function(e,n,l){return r.callExpression(this.file.addHelper("get"),[r.callExpression(r.memberExpression(r.identifier("Object"),r.identifier("getPrototypeOf")),[this.isStatic?this.className:r.memberExpression(this.className,r.identifier("prototype"))]),n?e:r.literal(e.name),l])},l.prototype.replace=function(){this.traverseLevel(this.methodNode.value,!0)};var a={enter:function(e,n,l,t){var a=t.topLevel,o=t.self;if(r.isFunction(e)&&!r.isArrowFunctionExpression(e))return o.traverseLevel(e,!1),this.skip();if(r.isProperty(e,{method:!0})||r.isMethodDefinition(e))return this.skip();var u=a?r.thisExpression:o.getThisReference.bind(o),s=o.specHandle;return o.isLoose&&(s=o.looseHandle),s.call(o,u,e,n)}};l.prototype.traverseLevel=function(e,n){var l={self:this,topLevel:n};this.scope.traverse(e,a,l)},l.prototype.getThisReference=function(){if(this.topLevelThisReference)return this.topLevelThisReference;var e=this.topLevelThisReference=this.scope.generateUidIdentifier("this");return this.methodNode.value.body.body.unshift(r.variableDeclaration("var",[r.variableDeclarator(this.topLevelThisReference,r.thisExpression())])),e},l.prototype.getLooseSuperProperty=function(e,n){var l=this.methodNode,t=l.key,a=this.superName||r.identifier("Function");return n.property===e?void 0:r.isCallExpression(n,{callee:e})?(n.arguments.unshift(r.thisExpression()),"constructor"===t.name?r.memberExpression(a,r.identifier("call")):(e=a,l.static||(e=r.memberExpression(e,r.identifier("prototype"))),e=r.memberExpression(e,t,l.computed),r.memberExpression(e,r.identifier("call")))):r.isMemberExpression(n)&&!l.static?r.memberExpression(a,r.identifier("prototype")):a},l.prototype.looseHandle=function(e,n,l){if(r.isIdentifier(n,{name:"super"}))return this.hasSuper=!0,this.getLooseSuperProperty(n,l);if(r.isCallExpression(n)){var t=n.callee;if(!r.isMemberExpression(t))return;if("super"!==t.object.name)return;this.hasSuper=!0,r.appendToMemberExpression(t,r.identifier("call")),n.arguments.unshift(e())}},l.prototype.specHandle=function(e,n,l){var a,s,i,c,d=this.methodNode;if(o(n,l))throw this.file.errorWithNode(n,t.get("classesIllegalBareSuper"));if(r.isCallExpression(n)){var p=n.callee;if(u(p,n)){if(a=d.key,s=d.computed,i=n.arguments,"constructor"!==d.key.name||!this.inClass){var f=d.key.name||"METHOD_NAME";throw this.file.errorWithNode(n,t.get("classesIllegalSuperCall",f))}}else r.isMemberExpression(p)&&u(p.object,p)&&(a=p.property,s=p.computed,i=n.arguments)}else if(r.isMemberExpression(n)&&u(n.object,n))a=n.property,s=n.computed;else if(r.isAssignmentExpression(n)&&u(n.left.object,n.left)&&"set"===d.kind)return this.hasSuper=!0,this.setSuperProperty(n.left.property,n.right,n.left.computed,e());if(a){this.hasSuper=!0,c=e();var g=this.getSuperProperty(a,s,c);return i?1===i.length&&r.isSpreadElement(i[0])?r.callExpression(r.memberExpression(g,r.identifier("apply")),[c,i[0].argument]):r.callExpression(r.memberExpression(g,r.identifier("call")),[c].concat(i)):g}};var o=function(e,n){return u(e,n)?r.isMemberExpression(n,{computed:!1})?!1:r.isCallExpression(n,{callee:e})?!1:!0:!1},u=function(e,n){return r.isIdentifier(e,{name:"super"})&&r.isReferenced(e,n)}},{"../../messages":27,"../../types":117}],40:[function(e,n){"use strict";function l(e,n){var l=new o(n);return l.parse(e)}n.exports=l;var t=e("../helpers/normalize-ast"),r=e("./transformer"),a=e("../helpers/object"),o=e("./file"),u=e("lodash/collection/each");l.fromAst=function(e,n,l){e=t(e);var r=new o(l);return r.addCode(n),r.transform(e),r.generate()},l._ensureTransformerNames=function(e,n){for(var t=[],r=0;r<n.length;r++){var a=n[r],o=l.deprecatedTransformerMap[a];if(o)console.error("The transformer "+a+" has been renamed to "+o),n.push(o);else if(l.transformers[a])t.push(a);else{if(!l.namespaces[a])throw new ReferenceError("Unknown transformer "+a+" specified in "+e);t=t.concat(l.namespaces[a])}}return t},l.transformerNamespaces=a(),l.transformers=a(),l.namespaces=a(),l.deprecatedTransformerMap=e("./transformers/deprecated"),l.moduleFormatters=e("./modules");var s=e("./transformers");u(s,function(e,n){var t=n.split(".")[0];l.namespaces[t]=l.namespaces[t]||[],l.namespaces[t].push(n),l.transformerNamespaces[n]=t,l.transformers[n]=new r(n,e)})},{"../helpers/normalize-ast":23,"../helpers/object":24,"./file":29,"./modules":48,"./transformer":53,"./transformers":79,"./transformers/deprecated":54,"lodash/collection/each":193}],41:[function(e,n){"use strict";function l(e){this.scope=e.scope,this.file=e,this.ids=a(),this.hasNonDefaultExports=!1,this.hasLocalExports=!1,this.hasLocalImports=!1,this.localImportOccurences=a(),this.localExports=a(),this.localImports=a(),this.getLocalExports(),this.getLocalImports(),this.remapAssignments()}n.exports=l;var t=e("../../messages"),r=e("lodash/object/extend"),a=e("../../helpers/object"),o=e("../../util"),u=e("../../types");l.prototype.doDefaultExportInterop=function(e){return e.default&&!this.noInteropRequireExport&&!this.hasNonDefaultExports},l.prototype.bumpImportOccurences=function(e){var n=e.source.value,l=this.localImportOccurences;l[n]=l[n]||0,l[n]+=e.specifiers.length};var s={enter:function(e,n,l,t){var a=e&&e.declaration;u.isExportDeclaration(e)&&(t.hasLocalImports=!0,a&&u.isStatement(a)&&r(t.localExports,u.getBindingIdentifiers(a)),e.default||(t.hasNonDefaultExports=!0),e.source&&t.bumpImportOccurences(e))}};l.prototype.getLocalExports=function(){this.file.scope.traverse(this.file.ast,s,this)};var i={enter:function(e,n,l,t){u.isImportDeclaration(e)&&(t.hasLocalImports=!0,r(t.localImports,u.getBindingIdentifiers(e)),t.bumpImportOccurences(e))}};l.prototype.getLocalImports=function(){this.file.scope.traverse(this.file.ast,i,this)};var c={enter:function(e,n,l,t){if(u.isUpdateExpression(e)&&t.isLocalReference(e.argument,l)){this.skip();var r=u.assignmentExpression(e.operator[0]+"=",e.argument,u.literal(1)),a=t.remapExportAssignment(r);if(u.isExpressionStatement(n)||e.prefix)return a;var o=[];o.push(a);var s;return s="--"===e.operator?"+":"-",o.push(u.binaryExpression(s,e.argument,u.literal(1))),u.sequenceExpression(o)}return u.isAssignmentExpression(e)&&t.isLocalReference(e.left,l)?(this.skip(),t.remapExportAssignment(e)):void 0}};l.prototype.remapAssignments=function(){this.hasLocalImports&&this.file.scope.traverse(this.file.ast,c,this)},l.prototype.isLocalReference=function(e){var n=this.localImports;return u.isIdentifier(e)&&n[e.name]&&n[e.name]!==e},l.prototype.remapExportAssignment=function(e){return u.assignmentExpression("=",e.left,u.assignmentExpression(e.operator,u.memberExpression(u.identifier("exports"),e.left),e.right))},l.prototype.isLocalReference=function(e,n){var l=this.localExports,t=e.name;return u.isIdentifier(e)&&l[t]&&l[t]===n.getBindingIdentifier(t)},l.prototype.getModuleName=function(){var e=this.file.opts;if(e.getModuleName)return e.getModuleName(e.filename);var n=e.filenameRelative,l="";if(e.moduleRoot&&(l=e.moduleRoot+"/"),!e.filenameRelative)return l+e.filename.replace(/^\//,"");if(e.sourceRoot){var t=new RegExp("^"+e.sourceRoot+"/?");n=n.replace(t,"")}return e.keepModuleIdExtensions||(n=n.replace(/\.(\w*?)$/,"")),l+=n,l=l.replace(/\\/g,"/")},l.prototype._pushStatement=function(e,n){return(u.isClass(e)||u.isFunction(e))&&e.id&&(n.push(u.toStatement(e)),e=e.id),e},l.prototype._hoistExport=function(e,n,l){return u.isFunctionDeclaration(e)&&(n._blockHoist=l||2),n},l.prototype.getExternalReference=function(e,n){var l=this.ids,t=e.source.value;return l[t]?l[t]:this.ids[t]=this._getExternalReference(e,n)},l.prototype.checkExportIdentifier=function(e){if(u.isIdentifier(e,{name:"__esModule"}))throw this.file.errorWithNode(e,t.get("modulesIllegalExportName",e.name))},l.prototype.exportSpecifier=function(e,n,l){if(n.source){var t=this.getExternalReference(n,l);u.isExportBatchSpecifier(e)?l.push(this.buildExportsWildcard(t,n)):(t=u.isSpecifierDefault(e)&&!this.noInteropRequireExport?u.callExpression(this.file.addHelper("interop-require"),[t]):u.memberExpression(t,u.getSpecifierId(e)),l.push(this.buildExportsAssignment(u.getSpecifierName(e),t,n)))}else l.push(this.buildExportsAssignment(u.getSpecifierName(e),e.id,n))},l.prototype.buildExportsWildcard=function(e){return u.expressionStatement(u.callExpression(this.file.addHelper("defaults"),[u.identifier("exports"),u.callExpression(this.file.addHelper("interop-require-wildcard"),[e])]))},l.prototype.buildExportsAssignment=function(e,n){return this.checkExportIdentifier(e),o.template("exports-assign",{VALUE:n,KEY:e},!0)},l.prototype.exportDeclaration=function(e,n){var l=e.declaration,t=l.id;e.default&&(t=u.identifier("default"));var r;if(u.isVariableDeclaration(l))for(var a=0;a<l.declarations.length;a++){var o=l.declarations[a];o.init=this.buildExportsAssignment(o.id,o.init,e).expression;var s=u.variableDeclaration(l.kind,[o]);0===a&&u.inherits(s,l),n.push(s)}else{var i=l;(u.isFunctionDeclaration(l)||u.isClassDeclaration(l))&&(i=l.id,n.push(l)),r=this.buildExportsAssignment(t,i,e),n.push(r),this._hoistExport(l,r)}}},{"../../helpers/object":24,"../../messages":27,"../../types":117,"../../util":119,"lodash/object/extend":275}],42:[function(e,n){"use strict";var l=e("../../util");n.exports=function(e){var n=function(){this.noInteropRequireImport=!0,this.noInteropRequireExport=!0,e.apply(this,arguments)};return l.inherits(n,e),n}},{"../../util":119}],43:[function(e,n){"use strict";n.exports=e("./_strict")(e("./amd"))},{"./_strict":42,"./amd":44}],44:[function(e,n){"use strict";function l(){r.apply(this,arguments)}n.exports=l;var t=e("./_default"),r=e("./common"),a=e("lodash/collection/includes"),o=e("lodash/object/values"),u=e("../../util"),s=e("../../types");u.inherits(l,t),l.prototype.init=r.prototype.init,l.prototype.buildDependencyLiterals=function(){var e=[];for(var n in this.ids)e.push(s.literal(n));return e},l.prototype.transform=function(e){var n=e.body,l=[s.literal("exports")];this.passModuleArg&&l.push(s.literal("module")),l=l.concat(this.buildDependencyLiterals()),l=s.arrayExpression(l);var t=o(this.ids);this.passModuleArg&&t.unshift(s.identifier("module")),t.unshift(s.identifier("exports"));var r=s.functionExpression(null,t,s.blockStatement(n)),a=[l,r],u=this.getModuleName();u&&a.unshift(s.literal(u));var i=s.callExpression(s.identifier("define"),a);e.body=[s.expressionStatement(i)]},l.prototype.getModuleName=function(){return this.file.opts.moduleIds?t.prototype.getModuleName.apply(this,arguments):null},l.prototype._getExternalReference=function(e){return this.scope.generateUidIdentifier(e.source.value)},l.prototype.importDeclaration=function(e){this.getExternalReference(e)},l.prototype.importSpecifier=function(e,n,l){var t=s.getSpecifierName(e),r=this.getExternalReference(n);a(this.file.dynamicImportedNoDefault,n)?this.ids[n.source.value]=r:s.isImportBatchSpecifier(e)||(r=a(this.file.dynamicImported,n)||!s.isSpecifierDefault(e)||this.noInteropRequireImport?s.memberExpression(r,s.getSpecifierId(e),!1):s.callExpression(this.file.addHelper("interop-require"),[r])),l.push(s.variableDeclaration("var",[s.variableDeclarator(t,r)]))},l.prototype.exportDeclaration=function(e){this.doDefaultExportInterop(e)&&(this.passModuleArg=!0),r.prototype.exportDeclaration.apply(this,arguments)}},{"../../types":117,"../../util":119,"./_default":41,"./common":46,"lodash/collection/includes":196,"lodash/object/values":279}],45:[function(e,n){"use strict";n.exports=e("./_strict")(e("./common"))},{"./_strict":42,"./common":46}],46:[function(e,n){"use strict";function l(){t.apply(this,arguments)}n.exports=l;var t=e("./_default"),r=e("lodash/collection/includes"),a=e("../../util"),o=e("../../types");a.inherits(l,t),l.prototype.init=function(){var e=this.file,n=e.scope;if(n.rename("module"),!this.noInteropRequireImport&&this.hasNonDefaultExports){var l="exports-module-declaration";this.file.isLoose("es6.modules")&&(l+="-loose"),e.ast.program.body.push(a.template(l,!0))}},l.prototype.importSpecifier=function(e,n,l){var t=o.getSpecifierName(e),a=this.getExternalReference(n,l);o.isSpecifierDefault(e)?(r(this.file.dynamicImportedNoDefault,n)||(a=this.noInteropRequireImport||r(this.file.dynamicImported,n)?o.memberExpression(a,o.identifier("default")):o.callExpression(this.file.addHelper("interop-require"),[a])),l.push(o.variableDeclaration("var",[o.variableDeclarator(t,a)]))):"ImportBatchSpecifier"===e.type?(this.noInteropRequireImport||(a=o.callExpression(this.file.addHelper("interop-require-wildcard"),[a])),l.push(o.variableDeclaration("var",[o.variableDeclarator(t,a)]))):l.push(o.variableDeclaration("var",[o.variableDeclarator(t,o.memberExpression(a,o.getSpecifierId(e)))]))},l.prototype.importDeclaration=function(e,n){n.push(a.template("require",{MODULE_NAME:e.source},!0))},l.prototype.exportDeclaration=function(e,n){if(this.doDefaultExportInterop(e)){var l=e.declaration,r=a.template("exports-default-assign",{VALUE:this._pushStatement(l,n)},!0);return o.isFunctionDeclaration(l)&&(r._blockHoist=3),void n.push(r)}t.prototype.exportDeclaration.apply(this,arguments)},l.prototype._getExternalReference=function(e,n){var l=e.source.value,t=o.callExpression(o.identifier("require"),[e.source]);if(this.localImportOccurences[l]>1){var r=this.scope.generateUidIdentifier(l);return n.push(o.variableDeclaration("var",[o.variableDeclarator(r,t)])),r}return t}},{"../../types":117,"../../util":119,"./_default":41,"lodash/collection/includes":196}],47:[function(e,n){"use strict";function l(){}n.exports=l;var t=e("../../types");l.prototype.exportDeclaration=function(e,n){var l=t.toStatement(e.declaration,!0);l&&n.push(t.inherits(l,e))},l.prototype.importDeclaration=l.prototype.importSpecifier=l.prototype.exportSpecifier=function(){}},{"../../types":117}],48:[function(e,n){n.exports={commonStrict:e("./common-strict"),amdStrict:e("./amd-strict"),umdStrict:e("./umd-strict"),common:e("./common"),system:e("./system"),ignore:e("./ignore"),amd:e("./amd"),umd:e("./umd")}},{"./amd":44,"./amd-strict":43,"./common":46,"./common-strict":45,"./ignore":47,"./system":49,"./umd":51,"./umd-strict":50}],49:[function(e,n){"use strict";function l(e){this.exportIdentifier=e.scope.generateUidIdentifier("export"),this.noInteropRequireExport=!0,this.noInteropRequireImport=!0,t.apply(this,arguments)}n.exports=l;var t=e("./_default"),r=e("./amd"),a=e("../../util"),o=e("lodash/array/last"),u=e("lodash/collection/each"),s=e("lodash/collection/map"),i=e("../../types");
a.inherits(l,r),l.prototype.init=function(){},l.prototype._addImportSource=function(e,n){return e._importSource=n.source&&n.source.value,e},l.prototype.buildExportsWildcard=function(e,n){var l=this.scope.generateUidIdentifier("key"),t=i.memberExpression(e,l,!0),r=i.variableDeclaration("var",[i.variableDeclarator(l)]),a=e,o=i.blockStatement([i.expressionStatement(this.buildExportCall(l,t))]);return this._addImportSource(i.forInStatement(r,a,o),n)},l.prototype.buildExportsAssignment=function(e,n,l){var t=this.buildExportCall(i.literal(e.name),n,!0);return this._addImportSource(t,l)},l.prototype.remapExportAssignment=function(e){return this.buildExportCall(i.literal(e.left.name),e)},l.prototype.buildExportCall=function(e,n,l){var t=i.callExpression(this.exportIdentifier,[e,n]);return l?i.expressionStatement(t):t},l.prototype.importSpecifier=function(e,n,l){r.prototype.importSpecifier.apply(this,arguments),this._addImportSource(o(l),n)};var c={enter:function(e,n,l,t){e._importSource===t.source&&(i.isVariableDeclaration(e)?u(e.declarations,function(e){t.hoistDeclarators.push(i.variableDeclarator(e.id)),t.nodes.push(i.expressionStatement(i.assignmentExpression("=",e.id,e.init)))}):t.nodes.push(e),this.remove())}};l.prototype.buildRunnerSetters=function(e,n){var l=this.file.scope;return i.arrayExpression(s(this.ids,function(t,r){var a={source:r,nodes:[],hoistDeclarators:n};return l.traverse(e,c,a),i.functionExpression(null,[t],i.blockStatement(a.nodes))}))};var d={enter:function(e,n,l,t){if(i.isFunction(e))return this.skip();if(i.isVariableDeclaration(e)){if("var"!==e.kind&&!i.isProgram(n))return;if(e._blockHoist)return;for(var r=[],a=0;a<e.declarations.length;a++){var o=e.declarations[a];if(t.push(i.variableDeclarator(o.id)),o.init){var u=i.expressionStatement(i.assignmentExpression("=",o.id,o.init));r.push(u)}}if(i.isFor(n)){if(n.left===e)return e.declarations[0].id;if(n.init===e)return i.toSequenceExpression(r,l)}return r}}},p={enter:function(e,n,l,t){i.isFunction(e)&&this.skip(),(i.isFunctionDeclaration(e)||e._blockHoist)&&(t.push(e),this.remove())}};l.prototype.transform=function(e){var n=[],l=this.getModuleName(),t=i.literal(l),r=i.blockStatement(e.body),o=a.template("system",{MODULE_NAME:t,MODULE_DEPENDENCIES:i.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(r,n),EXECUTE:i.functionExpression(null,[],r)},!0),u=o.expression.arguments[2].body.body;l||o.expression.arguments.shift();var s=u.pop();if(this.file.scope.traverse(r,d,n),n.length){var c=i.variableDeclaration("var",n);c._blockHoist=!0,u.unshift(c)}this.file.scope.traverse(r,p,u),u.push(s),e.body=[o]}},{"../../types":117,"../../util":119,"./_default":41,"./amd":44,"lodash/array/last":189,"lodash/collection/each":193,"lodash/collection/map":197}],50:[function(e,n){"use strict";n.exports=e("./_strict")(e("./umd"))},{"./_strict":42,"./umd":51}],51:[function(e,n){"use strict";function l(){t.apply(this,arguments)}n.exports=l;var t=e("./amd"),r=e("../../util"),a=e("../../types"),o=e("lodash/object/values");r.inherits(l,t),l.prototype.transform=function(e){var n=e.body,l=[];for(var t in this.ids)l.push(a.literal(t));var u=o(this.ids),s=[a.identifier("exports")];this.passModuleArg&&s.push(a.identifier("module")),s=s.concat(u);var i=a.functionExpression(null,s,a.blockStatement(n)),c=[a.literal("exports")];this.passModuleArg&&c.push(a.literal("module")),c=c.concat(l),c=[a.arrayExpression(c)];var d=r.template("test-exports"),p=r.template("test-module"),f=this.passModuleArg?a.logicalExpression("&&",d,p):d,g=[a.identifier("exports")];this.passModuleArg&&g.push(a.identifier("module")),g=g.concat(l.map(function(e){return a.callExpression(a.identifier("require"),[e])}));var h=this.getModuleName();h&&c.unshift(a.literal(h));var m=r.template("umd-runner-body",{AMD_ARGUMENTS:c,COMMON_TEST:f,COMMON_ARGUMENTS:g}),y=a.callExpression(m,[i]);e.body=[a.expressionStatement(y)]}},{"../../types":117,"../../util":119,"./amd":44,"lodash/object/values":279}],52:[function(e,n){function l(e,n){this.transformer=n,this.shouldRun=!n.check,this.handlers=n.handlers,this.file=e}n.exports=l;var t=e("lodash/collection/includes");l.prototype.canRun=function(){var e=this.transformer,n=this.file.opts,l=e.key;if("_"===l[0])return!0;var r=n.blacklist;if(r.length&&t(r,l))return!1;var a=n.whitelist;return a.length?t(a,l):e.optional&&!t(n.optional,l)?!1:e.experimental&&!n.experimental?!1:e.playground&&!n.playground?!1:!0},l.prototype.checkNode=function(e){var n=this.transformer.check;return n?this.shouldRun=n(e):!0},l.prototype.transform=function(){if(this.shouldRun){var e=this.file;e.debug("Running transformer "+this.transformer.key),e.scope.traverse(e.ast,this.handlers,e)}}},{"lodash/collection/includes":196}],53:[function(e,n){"use strict";function l(e,n,l){n=u({},n);var t=function(e){var l=n[e];return delete n[e],l};this.manipulateOptions=t("manipulateOptions"),this.check=t("check"),this.post=t("post"),this.pre=t("pre"),this.experimental=!!t("experimental"),this.playground=!!t("playground"),this.secondPass=!!t("secondPass"),this.optional=!!t("optional"),this.handlers=this.normalize(n),this.opts=l||{},this.key=e}n.exports=l;var t=e("./transformer-pass"),r=e("lodash/lang/isFunction"),a=e("../traversal"),o=e("lodash/lang/isObject"),u=e("lodash/object/assign"),s=e("lodash/collection/each");l.prototype.normalize=function(e){var n=this;return r(e)&&(e={ast:e}),a.explode(e),s(e,function(l,t){return"_"===t[0]?void(n[t]=l):void("enter"!==t&&"exit"!==t&&(r(l)&&(l={enter:l}),o(l)&&(l.enter||(l.enter=function(){}),l.exit||(l.exit=function(){}),e[t]=l)))}),e},l.prototype.buildPass=function(e){return new t(e,this)}},{"../traversal":112,"./transformer-pass":52,"lodash/collection/each":193,"lodash/lang/isFunction":266,"lodash/lang/isObject":269,"lodash/object/assign":273}],54:[function(e,n){n.exports={}},{}],55:[function(e,n,l){"use strict";var t=e("../../../types");l.MemberExpression=function(e){var n=e.property;e.computed&&t.isLiteral(n)&&t.isValidIdentifier(n.value)?(e.property=t.identifier(n.value),e.computed=!1):e.computed||!t.isIdentifier(n)||t.isValidIdentifier(n.name)||(e.property=t.literal(n.name),e.computed=!0)}},{"../../../types":117}],56:[function(e,n,l){"use strict";var t=e("../../../types");l.Property=function(e){var n=e.key;t.isLiteral(n)&&t.isValidIdentifier(n.value)?(e.key=t.identifier(n.value),e.computed=!1):e.computed||!t.isIdentifier(n)||t.isValidIdentifier(n.name)||(e.key=t.literal(n.name))}},{"../../../types":117}],57:[function(e,n,l){"use strict";var t=e("../../helpers/define-map"),r=e("../../../types");l.check=function(e){return r.isProperty(e)&&("get"===e.kind||"set"===e.kind)},l.ObjectExpression=function(e){var n={},l=!1;return e.properties=e.properties.filter(function(e){return"get"===e.kind||"set"===e.kind?(l=!0,t.push(n,e.key,e.kind,e.computed,e.value),!1):!0}),l?r.callExpression(r.memberExpression(r.identifier("Object"),r.identifier("defineProperties")),[e,t.build(n)]):void 0}},{"../../../types":117,"../../helpers/define-map":34}],58:[function(e,n,l){"use strict";var t=e("../../../types");l.check=t.isArrowFunctionExpression,l.ArrowFunctionExpression=function(e){return t.ensureBlock(e),e._aliasFunction="arrow",e.expression=!1,e.type="FunctionExpression",e}},{"../../../types":117}],59:[function(e,n,l){"use strict";var t=e("../../../types"),r={enter:function(e,n,l,r){if(t.isReferencedIdentifier(e,n)){var a=r.letRefs[e.name];if(a&&l.getBindingIdentifier(e.name)===a){var o=t.callExpression(r.file.addHelper("temporal-assert-defined"),[e,t.literal(e.name),r.file.addHelper("temporal-undefined")]);return this.skip(),t.isAssignmentExpression(n)||t.isUpdateExpression(n)?void(n._ignoreBlockScopingTDZ||this.parentPath.replaceNode(t.sequenceExpression([o,n]))):t.logicalExpression("&&",o,e)}}}};l.optional=!0,l.Loop=l.Program=l.BlockStatement=function(e,n,l,t){var a=e._letReferences;if(a){var o={letRefs:a,file:t};l.traverse(e,r,o)}}},{"../../../types":117}],60:[function(e,n,l){"use strict";function t(e,n,l,t,r){this.loopParent=e,this.parent=l,this.scope=t,this.block=n,this.file=r,this.outsideLetReferences=u(),this.hasLetReferences=!1,this.letReferences=n._letReferences=u(),this.body=[]}function r(e,n,l,t){if(i.isReferencedIdentifier(e,n)){var r=t[e.name];if(r){var a=l.getBindingIdentifier(e.name);a===r.binding?e.name=r.uid:this&&this.skip()}}}function a(e,n,l,t){r(e,n,l,t),l.traverse(e,m,t)}var o=e("../../../traversal"),u=e("../../../helpers/object"),s=e("../../../util"),i=e("../../../types"),c=e("lodash/object/values"),d=e("lodash/object/extend");l.check=function(e){return i.isVariableDeclaration(e)&&("let"===e.kind||"const"===e.kind)};var p=function(e,n){if(!i.isVariableDeclaration(e))return!1;if(e._let)return!0;if("let"!==e.kind)return!1;if(f(e,n))for(var l=0;l<e.declarations.length;l++){var t=e.declarations[l];t.init=t.init||i.identifier("undefined")}return e._let=!0,e.kind="var",!0},f=function(e,n){return!i.isFor(n)||i.isFor(n)&&n.left!==e},g=function(e,n){return i.isVariableDeclaration(e,{kind:"var"})&&!p(e,n)},h=function(e){for(var n=0;n<e.length;n++)delete e[n]._let};l.VariableDeclaration=function(e,n,l,t){if(p(e,n)&&f(e)&&t.transformers["es6.blockScopingTDZ"].canRun()){for(var r=[e],a=0;a<e.declarations.length;a++){var o=e.declarations[a];if(o.init){var u=i.assignmentExpression("=",o.id,o.init);u._ignoreBlockScopingTDZ=!0,r.push(i.expressionStatement(u))}o.init=t.addHelper("temporal-undefined")}return e._blockHoist=2,r}},l.Loop=function(e,n,l,r){var a=e.left||e.init;p(a,e)&&(i.ensureBlock(e),e.body._letDeclarators=[a]);var o=new t(e,e.body,n,l,r);o.run()},l.Program=l.BlockStatement=function(e,n,l,r){if(!i.isLoop(n)){var a=new t(!1,e,n,l,r);a.run()}},t.prototype.run=function(){var e=this.block;if(!e._letDone){e._letDone=!0;var n=this.getLetReferences();i.isFunction(this.parent)||i.isProgram(this.block)||this.hasLetReferences&&(n?this.wrapClosure():this.remap())}};var m={enter:r};t.prototype.remap=function(){var e=!1,n=this.letReferences,l=this.scope,t=u();for(var r in n){var o=n[r];if(l.parentHasBinding(r)||l.hasGlobal(r)){var s=l.generateUidIdentifier(o.name).name;o.name=s,e=!0,t[r]=t[s]={binding:o,uid:s}}}if(e){var i=this.loopParent;i&&(a(i.right,i,l,t),a(i.test,i,l,t),a(i.update,i,l,t)),l.traverse(this.block,m,t)}},t.prototype.wrapClosure=function(){var e=this.block,n=this.outsideLetReferences;if(this.loopParent)for(var l in n){var t=n[l];this.scope.hasGlobal(t.name)&&(delete n[t.name],delete this.letReferences[t.name],this.scope.rename(t.name),this.letReferences[t.name]=t,n[t.name]=t)}this.has=this.checkLoop(),this.hoistVarDeclarations();var r=c(n),a=i.functionExpression(null,r,i.blockStatement(e.body));a._aliasFunction=!0,e.body=this.body;var u=i.callExpression(a,r),s=this.scope.generateUidIdentifier("ret"),d=o.hasType(a.body,this.scope,"YieldExpression",i.FUNCTION_TYPES);d&&(a.generator=!0,u=i.yieldExpression(u,!0));var p=o.hasType(a.body,this.scope,"AwaitExpression",i.FUNCTION_TYPES);p&&(a.async=!0,u=i.awaitExpression(u,!0)),this.build(s,u)};var y={enter:function(e,n,l,t){i.isReferencedIdentifier(e,n)&&(l.hasOwnBinding(e.name)||t.letReferences[e.name]&&(t.closurify=!0))}},x={enter:function(e,n,l,t){return i.isFunction(e)?(l.traverse(e,y,t),this.skip()):void 0}};t.prototype.getLetReferences=function(){for(var e,n=this.block,l=n._letDeclarators||[],t=0;t<l.length;t++)e=l[t],d(this.outsideLetReferences,i.getBindingIdentifiers(e));if(n.body)for(t=0;t<n.body.length;t++)e=n.body[t],p(e,n)&&(l=l.concat(e.declarations));for(t=0;t<l.length;t++){e=l[t];var r=i.getBindingIdentifiers(e);d(this.letReferences,r),this.hasLetReferences=!0}if(this.hasLetReferences){h(l);var a={letReferences:this.letReferences,closurify:!1};return this.scope.traverse(this.block,x,a),a.closurify}};var b=function(e){return i.isBreakStatement(e)?"break":i.isContinueStatement(e)?"continue":void 0},_={enter:function(e,n,l,t){var r;if(i.isLoop(e)&&(t.ignoreLabeless=!0,l.traverse(e,_,t),t.ignoreLabeless=!1),i.isFunction(e)||i.isLoop(e))return this.skip();var a=b(e);if(a){if(e.label){if(t.innerLabels.indexOf(e.label.name)>=0)return;a=a+"|"+e.label.name}else{if(t.ignoreLabeless)return;if(i.isBreakStatement(e)&&i.isSwitchCase(n))return}t.hasBreakContinue=!0,t.map[a]=e,r=i.literal(a)}return i.isReturnStatement(e)&&(t.hasReturn=!0,r=i.objectExpression([i.property("init",i.identifier("v"),e.argument||i.identifier("undefined"))])),r?(r=i.returnStatement(r),i.inherits(r,e)):void 0}},v={enter:function(e,n,l,t){i.isLabeledStatement(e)&&t.innerLabels.push(e.label.name)}};t.prototype.checkLoop=function(){var e={hasBreakContinue:!1,ignoreLabeless:!1,innerLabels:[],hasReturn:!1,isLoop:!!this.loopParent,map:{}};return this.scope.traverse(this.block,v,e),this.scope.traverse(this.block,_,e),e};var I={enter:function(e,n,l,t){if(i.isForStatement(e))g(e.init,e)&&(e.init=i.sequenceExpression(t.pushDeclar(e.init)));else if(i.isFor(e))g(e.left,e)&&(e.left=e.left.declarations[0].id);else{if(g(e,n))return t.pushDeclar(e).map(i.expressionStatement);if(i.isFunction(e))return this.skip()}}};t.prototype.hoistVarDeclarations=function(){o(this.block,I,this.scope,this)},t.prototype.pushDeclar=function(e){this.body.push(i.variableDeclaration(e.kind,e.declarations.map(function(e){return i.variableDeclarator(e.id)})));for(var n=[],l=0;l<e.declarations.length;l++){var t=e.declarations[l];if(t.init){var r=i.assignmentExpression("=",t.id,t.init);n.push(i.inherits(r,t))}}return n},t.prototype.build=function(e,n){var l=this.has;l.hasReturn||l.hasBreakContinue?this.buildHas(e,n):this.body.push(i.expressionStatement(n))},t.prototype.buildHas=function(e,n){var l=this.body;l.push(i.variableDeclaration("var",[i.variableDeclarator(e,n)]));var t,r=this.loopParent,a=this.has,o=[];if(a.hasReturn&&(t=s.template("let-scoping-return",{RETURN:e})),a.hasBreakContinue){if(!r)throw new Error("Has no loop parent but we're trying to reassign breaks and continues, something is going wrong here.");for(var u in a.map)o.push(i.switchCase(i.literal(u),[a.map[u]]));if(a.hasReturn&&o.push(i.switchCase(null,[t])),1===o.length){var c=o[0];l.push(this.file.attachAuxiliaryComment(i.ifStatement(i.binaryExpression("===",e,c.test),c.consequent[0])))}else l.push(this.file.attachAuxiliaryComment(i.switchStatement(e,o)))}else a.hasReturn&&l.push(this.file.attachAuxiliaryComment(t))}},{"../../../helpers/object":24,"../../../traversal":112,"../../../types":117,"../../../util":119,"lodash/object/extend":275,"lodash/object/values":279}],61:[function(e,n,l){"use strict";function t(e,n,l,t){this.isStatement=t,this.scope=l,this.node=e,this.file=n,this.hasInstanceMutators=!1,this.hasStaticMutators=!1,this.instanceMutatorMap={},this.staticMutatorMap={},this.hasConstructor=!1,this.className=e.id||l.generateUidIdentifier("class"),this.superName=e.superClass||i.identifier("Function"),this.hasSuper=!!e.superClass,this.isLoose=n.isLoose("es6.classes")}var r=e("../../helpers/replace-supers"),a=e("../../helpers/name-method"),o=e("../../helpers/define-map"),u=e("../../../messages"),s=e("../../../util"),i=e("../../../types");l.check=i.isClass,l.ClassDeclaration=function(e,n,l,r){return new t(e,r,l,!0).run()},l.ClassExpression=function(e,n,l,r){return e.id||(i.isProperty(n)&&n.value===e&&!n.computed&&i.isIdentifier(n.key)&&(e.id=n.key),i.isVariableDeclarator(n)&&i.isIdentifier(n.id)&&(e.id=n.id)),new t(e,r,l,!1).run()},t.prototype.run=function(){var e,n=this.superName,l=this.className,t=this.file,r=this.body=[],a=i.blockStatement([i.expressionStatement(i.callExpression(t.addHelper("class-call-check"),[i.thisExpression(),l]))]);this.node.id?(e=i.functionDeclaration(l,[],a),r.push(e)):(e=i.functionExpression(null,[],a),r.push(i.variableDeclaration("var",[i.variableDeclarator(l,e)]))),this.constructor=e;var o=[],u=[];this.hasSuper&&(u.push(n),i.isIdentifier(n)||(n=this.scope.generateUidBasedOnNode(n,this.file)),o.push(n),this.superName=n,r.push(i.expressionStatement(i.callExpression(t.addHelper("inherits"),[l,n])))),this.buildBody(),i.inheritsComments(r[0],this.node);var s;return 1===r.length?s=i.toExpression(e):(r.push(i.returnStatement(l)),s=i.callExpression(i.functionExpression(null,o,i.blockStatement(r)),u)),this.isStatement?i.variableDeclaration("let",[i.variableDeclarator(l,s)]):s},t.prototype.buildBody=function(){for(var e=this.constructor,n=this.className,l=this.superName,t=this.node.body.body,a=this.body,u=0;u<t.length;u++){var c=t[u];if(i.isMethodDefinition(c)){var d=new r({methodNode:c,className:this.className,superName:this.superName,isStatic:c.static,isLoose:this.isLoose,scope:this.scope,file:this.file},!0);d.replace(),!c.computed&&i.isIdentifier(c.key,{name:"constructor"})||i.isLiteral(c.key,{value:"constructor"})?this.pushConstructor(c):this.pushMethod(c)}else i.isPrivateDeclaration(c)?(this.closure=!0,a.unshift(c)):i.isClassProperty(c)&&this.pushProperty(c)}if(!this.hasConstructor&&this.hasSuper&&!i.isFalsyExpression(l)){var p="class-super-constructor-call";this.isLoose&&(p+="-loose"),e.body.body.push(s.template(p,{CLASS_NAME:n,SUPER_NAME:this.superName},!0))}var f,g;if(this.hasInstanceMutators&&(f=o.build(this.instanceMutatorMap)),this.hasStaticMutators&&(g=o.build(this.staticMutatorMap)),f||g){g=g||i.literal(null);var h=[n,g];f&&h.push(f),a.push(i.expressionStatement(i.callExpression(this.file.addHelper("prototype-properties"),h)))}},t.prototype.pushMethod=function(e){var n=e.key,l=e.kind;if(""===l){if(a.property(e,this.file,this.scope),this.isLoose){var t=this.className;e.static||(t=i.memberExpression(t,i.identifier("prototype"))),n=i.memberExpression(t,n,e.computed);var r=i.expressionStatement(i.assignmentExpression("=",n,e.value));return i.inheritsComments(r,e),void this.body.push(r)}l="value"}var u=this.instanceMutatorMap;e.static?(this.hasStaticMutators=!0,u=this.staticMutatorMap):this.hasInstanceMutators=!0,o.push(u,n,l,e.computed,e),o.push(u,n,"enumerable",e.computed,!1)},t.prototype.pushProperty=function(e){if(e.value){var n;e.static?(n=i.memberExpression(this.className,e.key),this.body.push(i.expressionStatement(i.assignmentExpression("=",n,e.value)))):(n=i.memberExpression(i.thisExpression(),e.key),this.constructor.body.body.unshift(i.expressionStatement(i.assignmentExpression("=",n,e.value))))}},t.prototype.pushConstructor=function(e){if(e.kind)throw this.file.errorWithNode(e,u.get("classesIllegalConstructorKind"));var n=this.constructor,l=e.value;this.hasConstructor=!0,i.inherits(n,l),i.inheritsComments(n,e),n._ignoreUserWhitespace=!0,n.params=l.params,n.body.body=n.body.body.concat(l.body.body)}},{"../../../messages":27,"../../../types":117,"../../../util":119,"../../helpers/define-map":34,"../../helpers/name-method":36,"../../helpers/replace-supers":39}],62:[function(e,n,l){"use strict";var t=e("../../../messages"),r=e("../../../types");l.check=function(e){return r.isVariableDeclaration(e,{kind:"const"})};var a={enter:function(e,n,l,a){if(r.isAssignmentExpression(e)||r.isUpdateExpression(e)){var o=r.getBindingIdentifiers(e);for(var u in o){var s=o[u],i=a.constants[u];if(i){var c=i.identifier;if(s!==c&&l.bindingIdentifierEquals(u,c))throw a.file.errorWithNode(s,t.get("readOnly",u))}}}else r.isScope(e,n)&&this.skip()}};l.Scopable=function(e,n,l,t){l.traverse(e,a,{constants:l.getAllBindingsOfKind("const"),file:t})},l.VariableDeclaration=function(e){"const"===e.kind&&(e.kind="let")}},{"../../../messages":27,"../../../types":117}],63:[function(e,n,l){"use strict";function t(e){this.blockHoist=e.blockHoist,this.operator=e.operator,this.nodes=e.nodes,this.scope=e.scope,this.file=e.file,this.kind=e.kind}var r=e("../../../messages"),a=e("../../../types");l.check=a.isPattern,t.prototype.buildVariableAssignment=function(e,n){var l=this.operator;a.isMemberExpression(e)&&(l="=");var t;return t=l?a.expressionStatement(a.assignmentExpression(l,e,n)):a.variableDeclaration(this.kind,[a.variableDeclarator(e,n)]),t._blockHoist=this.blockHoist,t},t.prototype.buildVariableDeclaration=function(e,n){var l=a.variableDeclaration("var",[a.variableDeclarator(e,n)]);return l._blockHoist=this.blockHoist,l},t.prototype.push=function(e,n){a.isObjectPattern(e)?this.pushObjectPattern(e,n):a.isArrayPattern(e)?this.pushArrayPattern(e,n):a.isAssignmentPattern(e)?this.pushAssignmentPattern(e,n):this.nodes.push(this.buildVariableAssignment(e,n))},t.prototype.get=function(){},t.prototype.pushAssignmentPattern=function(e,n){var l=this.scope.generateUidBasedOnNode(n),t=a.variableDeclaration("var",[a.variableDeclarator(l,n)]);t._blockHoist=this.blockHoist,this.nodes.push(t),this.nodes.push(this.buildVariableAssignment(e.left,a.conditionalExpression(a.binaryExpression("===",l,a.identifier("undefined")),e.right,l)))},t.prototype.pushObjectSpread=function(e,n,l,t){for(var r=[],o=0;o<e.properties.length;o++){var u=e.properties[o];if(o>=t)break;if(!a.isSpreadProperty(u)){var s=u.key;a.isIdentifier(s)&&(s=a.literal(u.key.name)),r.push(s)}}r=a.arrayExpression(r);var i=a.callExpression(this.file.addHelper("object-without-properties"),[n,r]);this.nodes.push(this.buildVariableAssignment(l.argument,i))},t.prototype.pushObjectProperty=function(e,n){a.isLiteral(e.key)&&(e.computed=!0);var l=e.value,t=a.memberExpression(n,e.key,e.computed);a.isPattern(l)?this.push(l,t):this.nodes.push(this.buildVariableAssignment(l,t))},t.prototype.pushObjectPattern=function(e,n){if(e.properties.length||this.nodes.push(a.expressionStatement(a.callExpression(this.file.addHelper("object-destructuring-empty"),[n]))),e.properties.length>1&&a.isMemberExpression(n)){var l=this.scope.generateUidBasedOnNode(n,this.file);this.nodes.push(this.buildVariableDeclaration(l,n)),n=l}for(var t=0;t<e.properties.length;t++){var r=e.properties[t];a.isSpreadProperty(r)?this.pushObjectSpread(e,n,r,t):this.pushObjectProperty(r,n)}};var o=function(e){for(var n=0;n<e.elements.length;n++)if(a.isRestElement(e.elements[n]))return!0;return!1};t.prototype.canUnpackArrayPattern=function(e,n){if(!a.isArrayExpression(n))return!1;if(e.elements.length<n.elements.length&&!o(e))return!1;for(var l=0;l<e.elements.length;l++)if(!e.elements[l])return!1;return!0},t.prototype.pushUnpackedArrayPattern=function(e,n){for(var l=0;l<e.elements.length;l++){var t=e.elements[l];a.isRestElement(t)?this.push(t.argument,a.arrayExpression(n.elements.slice(l))):this.push(t,n.elements[l])}},t.prototype.pushArrayPattern=function(e,n){if(e.elements){if(this.canUnpackArrayPattern(e,n))return this.pushUnpackedArrayPattern(e,n);var l=!o(e)&&e.elements.length,t=this.scope.toArray(n,l);a.isIdentifier(t)?n=t:(n=this.scope.generateUidBasedOnNode(n),this.nodes.push(this.buildVariableDeclaration(n,t)),this.scope.assignTypeGeneric(n.name,"Array"));for(var r=0;r<e.elements.length;r++){var u=e.elements[r];if(u){var s;a.isRestElement(u)?(s=this.scope.toArray(n),r>0&&(s=a.callExpression(a.memberExpression(s,a.identifier("slice")),[a.literal(r)])),u=u.argument):s=a.memberExpression(n,a.literal(r),!0),this.push(u,s)}}}},t.prototype.init=function(e,n){if(!a.isArrayExpression(n)&&!a.isMemberExpression(n)&&!a.isIdentifier(n)){var l=this.scope.generateUidBasedOnNode(n);this.nodes.push(this.buildVariableDeclaration(l,n)),n=l}this.push(e,n)},l.ForInStatement=l.ForOfStatement=function(e,n,l,r){var o=e.left;if(a.isPattern(o)){var u=l.generateUidIdentifier("ref");return e.left=a.variableDeclaration("var",[a.variableDeclarator(u)]),a.ensureBlock(e),void e.body.body.unshift(a.variableDeclaration("var",[a.variableDeclarator(o,u)]))}if(a.isVariableDeclaration(o)){var s=o.declarations[0].id;if(a.isPattern(s)){var i=l.generateUidIdentifier("ref");e.left=a.variableDeclaration(o.kind,[a.variableDeclarator(i,null)]);var c=[],d=new t({kind:o.kind,file:r,scope:l,nodes:c});d.init(s,i),a.ensureBlock(e);var p=e.body;p.body=c.concat(p.body)}}},l.Function=function(e,n,l,r){var o=[],u=!1;if(e.params=e.params.map(function(n,s){if(!a.isPattern(n))return n;u=!0;var i=l.generateUidIdentifier("ref"),c=new t({blockHoist:e.params.length-s,nodes:o,scope:l,file:r,kind:"var"});return c.init(n,i),i}),u){a.ensureBlock(e);var s=e.body;s.body=o.concat(s.body)}},l.CatchClause=function(e,n,l,r){var o=e.param;if(a.isPattern(o)){var u=l.generateUidIdentifier("ref");e.param=u;var s=[],i=new t({kind:"let",file:r,scope:l,nodes:s});return i.init(o,u),e.body.body=s.concat(e.body.body),e}},l.ExpressionStatement=function(e,n,l,r){var o=e.expression;if("AssignmentExpression"===o.type&&a.isPattern(o.left)&&!r.isConsequenceExpressionStatement(e)){var u=[],s=l.generateUidIdentifier("ref");u.push(a.variableDeclaration("var",[a.variableDeclarator(s,o.right)]));var i=new t({operator:o.operator,file:r,scope:l,nodes:u});return i.init(o.left,s),u}},l.AssignmentExpression=function(e,n,l,r){if(a.isPattern(e.left)){var o=l.generateUidIdentifier("temp");l.push({key:o.name,id:o});var u=[];u.push(a.assignmentExpression("=",o,e.right));var s=new t({operator:e.operator,file:r,scope:l,nodes:u});return s.init(e.left,o),u.push(o),a.toSequenceExpression(u,l)}};var u=function(e){for(var n=0;n<e.declarations.length;n++)if(a.isPattern(e.declarations[n].id))return!0;return!1};l.VariableDeclaration=function(e,n,l,o){if(!a.isForInStatement(n)&&!a.isForOfStatement(n)&&u(e)){for(var s,i=[],c=0;c<e.declarations.length;c++){s=e.declarations[c];var d=s.init,p=s.id,f=new t({nodes:i,scope:l,kind:e.kind,file:o});a.isPattern(p)&&d?(f.init(p,d),+c!==e.declarations.length-1&&a.inherits(i[i.length-1],s)):i.push(a.inherits(f.buildVariableAssignment(s.id,s.init),s))}if(!a.isProgram(n)&&!a.isBlockStatement(n)){for(s=null,c=0;c<i.length;c++){if(e=i[c],s=s||a.variableDeclaration(e.kind,[]),!a.isVariableDeclaration(e)&&s.kind!==e.kind)throw o.errorWithNode(e,r.get("invalidParentForThisNode"));s.declarations=s.declarations.concat(e.declarations)}return s}return i}}},{"../../../messages":27,"../../../types":117}],64:[function(e,n,l){"use strict";var t=e("../../../messages"),r=e("../../../util"),a=e("../../../types");l.check=a.isForOfStatement,l.ForOfStatement=function(e,n,l,t){var r=s;t.isLoose("es6.forOf")&&(r=u);var o=r(e,n,l,t),i=o.declar,c=o.loop,d=c.body;return a.inheritsComments(c,e),a.ensureBlock(e),i&&d.body.push(i),d.body=d.body.concat(e.body.body),a.inherits(c,e),c._scopeInfo=e._scopeInfo,c};var o={enter:function(e,n,l,t){if(a.isLoop(e))return t.ignoreLabeless=!0,l.traverse(e,o,t),t.ignoreLabeless=!1,this.skip();if(a.isBreakStatement(e)){if(!e.label&&t.ignoreLabeless)return;if(e.label&&e.label.name!==t.label)return;var r=a.expressionStatement(a.callExpression(a.memberExpression(t.iteratorKey,a.identifier("return")),[]));return t.wrapReturn&&(r=t.wrapReturn(r)),[r,e]}}},u=function(e,n,l,u){var s,i,c=e.left;if(a.isIdentifier(c)||a.isPattern(c))i=c;else{if(!a.isVariableDeclaration(c))throw u.errorWithNode(c,t.get("unknownForHead",c.type));i=l.generateUidIdentifier("ref"),s=a.variableDeclaration(c.kind,[a.variableDeclarator(c.declarations[0].id,i)])}var d=l.generateUidIdentifier("iterator"),p=l.generateUidIdentifier("isArray"),f=r.template("for-of-loose",{LOOP_OBJECT:d,IS_ARRAY:p,OBJECT:e.right,INDEX:l.generateUidIdentifier("i"),ID:i});return s||f.body.body.shift(),l.traverse(e,o,{iteratorKey:d,wrapReturn:function(e){return a.ifStatement(a.unaryExpression("!",p,!0),e)},label:a.isLabeledStatement(n)&&n.label.name}),{declar:s,loop:f}},s=function(e,n,l,u){var s,i=e.left,c=l.generateUidIdentifier("step"),d=a.memberExpression(c,a.identifier("value"));if(a.isIdentifier(i)||a.isPattern(i))s=a.expressionStatement(a.assignmentExpression("=",i,d));else{if(!a.isVariableDeclaration(i))throw u.errorWithNode(i,t.get("unknownForHead",i.type));s=a.variableDeclaration(i.kind,[a.variableDeclarator(i.declarations[0].id,d)])}var p=l.generateUidIdentifier("iterator"),f=r.template("for-of",{ITERATOR_KEY:p,STEP_KEY:c,OBJECT:e.right});return l.traverse(e,o,{iteratorKey:p,label:a.isLabeledStatement(n)&&n.label.name}),{declar:s,loop:f}}},{"../../../messages":27,"../../../types":117,"../../../util":119}],65:[function(e,n,l){"use strict";var t=e("../../../types");l.check=e("../internal/modules").check,l.ImportDeclaration=function(e,n,l,t){var r=[];if(e.specifiers.length)for(var a=0;a<e.specifiers.length;a++)t.moduleFormatter.importSpecifier(e.specifiers[a],e,r,n);else t.moduleFormatter.importDeclaration(e,r,n);return 1===r.length&&(r[0]._blockHoist=e._blockHoist),r},l.ExportDeclaration=function(e,n,l,r){var a,o=[];if(e.declaration){if(t.isVariableDeclaration(e.declaration)){var u=e.declaration.declarations[0];u.init=u.init||t.identifier("undefined")}r.moduleFormatter.exportDeclaration(e,o,n)}else if(e.specifiers)for(a=0;a<e.specifiers.length;a++)r.moduleFormatter.exportSpecifier(e.specifiers[a],e,o,n);if(e._blockHoist)for(a=0;a<o.length;a++)o[a]._blockHoist=e._blockHoist;return o}},{"../../../types":117,"../internal/modules":85}],66:[function(e,n,l){"use strict";var t=e("../../helpers/replace-supers"),r=e("../../../types");l.check=function(e){return r.isIdentifier(e,{name:"super"})},l.Property=function(e,n,l,a){if(e.method){var o=e.value,u=l.generateUidIdentifier("this"),s=new t({topLevelThisReference:u,methodNode:e,className:u,isStatic:!0,scope:l,file:a});s.replace(),s.hasSuper&&o.body.body.unshift(r.variableDeclaration("var",[r.variableDeclarator(u,r.thisExpression())]))}}},{"../../../types":117,"../../helpers/replace-supers":39}],67:[function(e,n,l){"use strict";var t=e("../../../util"),r=e("../../../types");l.check=function(e){return r.isFunction(e)&&a(e)};var a=function(e){for(var n=0;n<e.params.length;n++)if(!r.isIdentifier(e.params[n]))return!0;return!1},o={enter:function(e,n,l,t){r.isReferencedIdentifier(e,n)&&t.scope.hasOwnBinding(e.name)&&(t.scope.bindingIdentifierEquals(e.name,e)||(t.iife=!0,this.stop()))}};l.Function=function(e,n,l,u){if(a(e)){r.ensureBlock(e);var s=[],i=r.identifier("arguments");i._ignoreAliasFunctions=!0;for(var c=0,d={iife:!1,scope:l},p=function(n,l,a){var o=t.template("default-parameter",{VARIABLE_NAME:n,DEFAULT_VALUE:l,ARGUMENT_KEY:r.literal(a),ARGUMENTS:i},!0);u.checkNode(o),o._blockHoist=e.params.length-a,s.push(o)},f=0;f<e.params.length;f++){var g=e.params[f];if(r.isAssignmentPattern(g)){var h=g.left,m=g.right,y=l.generateUidIdentifier("x");y._isDefaultPlaceholder=!0,e.params[f]=y,d.iife||(r.isIdentifier(m)&&l.hasOwnBinding(m.name)?d.iife=!0:l.traverse(m,o,d)),p(h,m,f)}else r.isRestElement(g)||(c=f+1),r.isIdentifier(g)||l.traverse(g,o,d),u.transformers["es6.blockScopingTDZ"].canRun()&&p(g,r.identifier("undefined"),f)}if(e.params=e.params.slice(0,c),d.iife){var x=r.functionExpression(null,[],e.body,e.generator);x._aliasFunction=!0,s.push(r.returnStatement(r.callExpression(x,[]))),e.body=r.blockStatement(s)}else e.body.body=s.concat(e.body.body)}}},{"../../../types":117,"../../../util":119}],68:[function(e,n,l){"use strict";var t=e("../../../util"),r=e("../../../types");l.check=r.isRestElement;var a=function(e){return r.isRestElement(e.params[e.params.length-1])};l.Function=function(e,n,l){if(a(e)){var o=e.params.pop().argument,u=r.identifier("arguments");u._ignoreAliasFunctions=!0;var s=r.literal(e.params.length),i=l.generateUidIdentifier("key"),c=l.generateUidIdentifier("len"),d=i,p=c;if(e.params.length&&(d=r.binaryExpression("-",i,s),p=r.conditionalExpression(r.binaryExpression(">",c,s),r.binaryExpression("-",c,s),r.literal(0))),r.isPattern(o)){var f=o;o=l.generateUidIdentifier("ref");var g=r.variableDeclaration("var",[r.variableDeclarator(f,o)]);g._blockHoist=e.params.length+1,e.body.body.unshift(g)}l.assignTypeGeneric(o.name,"Array");var h=t.template("rest",{ARGUMENTS:u,ARRAY_KEY:d,ARRAY_LEN:p,START:s,ARRAY:o,KEY:i,LEN:c});h._blockHoist=e.params.length+1,e.body.body.unshift(h)}}},{"../../../types":117,"../../../util":119}],69:[function(e,n,l){"use strict";var t=e("../../../types");l.check=function(e){return t.isProperty(e)&&e.computed},l.ObjectExpression=function(e,n,l,o){for(var u=!1,s=0;s<e.properties.length&&!(u=t.isProperty(e.properties[s],{computed:!0,kind:"init"}));s++);if(u){var i=[],c=l.generateUidBasedOnNode(n),d=[],p=t.functionExpression(null,[],t.blockStatement(d));p._aliasFunction=!0;var f=a;o.isLoose("es6.properties.computed")&&(f=r);
var g=f(e,d,c,i,o);return g?g:(d.unshift(t.variableDeclaration("var",[t.variableDeclarator(c,t.objectExpression(i))])),d.push(t.returnStatement(c)),t.callExpression(p,[]))}};var r=function(e,n,l){for(var r=0;r<e.properties.length;r++){var a=e.properties[r];n.push(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(l,a.key,a.computed||t.isLiteral(a.key)),a.value)))}},a=function(e,n,l,r,a){for(var o,u,s=e.properties,i=0;i<s.length;i++)o=s[i],"init"===o.kind&&(u=o.key,!o.computed&&t.isIdentifier(u)&&(o.key=t.literal(u.name)));var c=!1;for(i=0;i<s.length;i++)o=s[i],o.computed&&(c=!0),("init"!==o.kind||!c||t.isLiteral(t.toComputedKey(o,o.key),{value:"__proto__"}))&&(r.push(o),s[i]=null);for(i=0;i<s.length;i++)if(o=s[i]){u=o.key;var d;d=o.computed&&t.isMemberExpression(u)&&t.isIdentifier(u.object,{name:"Symbol"})?t.assignmentExpression("=",t.memberExpression(l,u,!0),o.value):t.callExpression(a.addHelper("define-property"),[l,u,o.value]),n.push(t.expressionStatement(d))}if(1===n.length){var p=n[0].expression;if(t.isCallExpression(p))return p.arguments[0]=t.objectExpression(r),p}}},{"../../../types":117}],70:[function(e,n,l){"use strict";var t=e("lodash/lang/clone"),r=e("../../../types");l.check=function(e){return r.isProperty(e)&&(e.method||e.shorthand)},l.Property=function(e){e.method&&(e.method=!1),e.shorthand&&(e.shorthand=!1,e.key=r.removeComments(t(e.key)))}},{"../../../types":117,"lodash/lang/clone":260}],71:[function(e,n,l){"use strict";var t=e("lodash/collection/includes"),r=e("../../../types");l.check=r.isSpreadElement;var a=function(e,n){return n.toArray(e.argument,!0)},o=function(e){for(var n=0;n<e.length;n++)if(r.isSpreadElement(e[n]))return!0;return!1},u=function(e,n){for(var l=[],t=[],o=function(){t.length&&(l.push(r.arrayExpression(t)),t=[])},u=0;u<e.length;u++){var s=e[u];r.isSpreadElement(s)?(o(),l.push(a(s,n))):t.push(s)}return o(),l};l.ArrayExpression=function(e,n,l){var t=e.elements;if(o(t)){var a=u(t,l),s=a.shift();return r.isArrayExpression(s)||(a.unshift(s),s=r.arrayExpression([])),r.callExpression(r.memberExpression(s,r.identifier("concat")),a)}},l.CallExpression=function(e,n,l){var t=e.arguments;if(o(t)){var a=r.identifier("undefined");e.arguments=[];var s;s=1===t.length&&"arguments"===t[0].argument.name?[t[0].argument]:u(t,l);var i=s.shift();e.arguments.push(s.length?r.callExpression(r.memberExpression(i,r.identifier("concat")),s):i);var c=e.callee;if(r.isMemberExpression(c)){var d=l.generateTempBasedOnNode(c.object);d?(c.object=r.assignmentExpression("=",d,c.object),a=d):a=c.object,r.appendToMemberExpression(c,r.identifier("apply"))}else e.callee=r.memberExpression(e.callee,r.identifier("apply"));e.arguments.unshift(a)}},l.NewExpression=function(e,n,l,a){var s=e.arguments;if(o(s)){var i=r.isIdentifier(e.callee)&&t(r.NATIVE_TYPE_NAMES,e.callee.name),c=u(s,l);i&&c.unshift(r.arrayExpression([r.literal(null)]));var d=c.shift();return s=c.length?r.callExpression(r.memberExpression(d,r.identifier("concat")),c):d,i?r.newExpression(r.callExpression(r.memberExpression(a.addHelper("bind"),r.identifier("apply")),[e.callee,s]),[]):r.callExpression(a.addHelper("apply-constructor"),[e.callee,s])}}},{"../../../types":117,"lodash/collection/includes":196}],72:[function(e,n,l){"use strict";function t(e){return c.blockStatement([c.returnStatement(e)])}function r(e,n,l){this.hasTailRecursion=!1,this.needsArguments=!1,this.setsArguments=!1,this.needsThis=!1,this.ownerId=e.id,this.vars=[],this.scope=n,this.file=l,this.node=e}var a=e("lodash/collection/reduceRight"),o=e("../../../messages"),u=e("lodash/array/flatten"),s=e("../../../util"),i=e("lodash/collection/map"),c=e("../../../types");r.prototype.getArgumentsId=function(){return this.argumentsId=this.argumentsId||this.scope.generateUidIdentifier("arguments")},r.prototype.getThisId=function(){return this.thisId=this.thisId||this.scope.generateUidIdentifier("this")},r.prototype.getLeftId=function(){return this.leftId=this.leftId||this.scope.generateUidIdentifier("left")},r.prototype.getFunctionId=function(){return this.functionId=this.functionId||this.scope.generateUidIdentifier("function")},r.prototype.getAgainId=function(){return this.againId=this.againId||this.scope.generateUidIdentifier("again")},r.prototype.getParams=function(){var e=this.params;if(!e){e=this.node.params,this.paramDecls=[];for(var n=0;n<e.length;n++){var l=e[n];l._isDefaultPlaceholder||this.paramDecls.push(c.variableDeclarator(l,e[n]=this.scope.generateUidIdentifier("x")))}}return this.params=e},r.prototype.hasDeopt=function(){var e=this.scope.getBindingInfo(this.ownerId.name);return e&&e.reassigned},r.prototype.run=function(){var e=this.scope,n=this.node,l=this.ownerId;if(l&&(e.traverse(n,d,this),this.hasTailRecursion)){if(this.hasDeopt())return void this.file.logDeopt(n,o.get("tailCallReassignmentDeopt"));e.traverse(n,p,this),this.needsThis&&this.needsArguments||e.traverse(n,f,this);var t=c.ensureBlock(n).body;if(this.vars.length>0){var r=u(i(this.vars,function(e){return e.declarations},this)),g=a(r,function(e,n){return c.assignmentExpression("=",n.id,e)},c.identifier("undefined"));t.unshift(c.expressionStatement(g))}var h=this.paramDecls;h.length>0&&t.unshift(c.variableDeclaration("var",h)),t.unshift(c.expressionStatement(c.assignmentExpression("=",this.getAgainId(),c.literal(!1)))),n.body=s.template("tail-call-body",{AGAIN_ID:this.getAgainId(),THIS_ID:this.thisId,ARGUMENTS_ID:this.argumentsId,FUNCTION_ID:this.getFunctionId(),BLOCK:n.body});var m=[];if(this.needsThis&&m.push(c.variableDeclarator(this.getThisId(),c.thisExpression())),this.needsArguments||this.setsArguments){var y=c.variableDeclarator(this.getArgumentsId());this.needsArguments&&(y.init=c.identifier("arguments")),m.push(y)}var x=this.leftId;x&&m.push(c.variableDeclarator(x)),m.length>0&&n.body.body.unshift(c.variableDeclaration("var",m))}},r.prototype.subTransform=function(e){if(e){var n=this["subTransform"+e.type];return n?n.call(this,e):void 0}},r.prototype.subTransformConditionalExpression=function(e){var n=this.subTransform(e.consequent),l=this.subTransform(e.alternate);return n||l?(e.type="IfStatement",e.consequent=n?c.toBlock(n):t(e.consequent),e.alternate=l?c.isIfStatement(l)?l:c.toBlock(l):t(e.alternate),[e]):void 0},r.prototype.subTransformLogicalExpression=function(e){var n=this.subTransform(e.right);if(n){var l=this.getLeftId(),r=c.assignmentExpression("=",l,e.left);return"&&"===e.operator&&(r=c.unaryExpression("!",r)),[c.ifStatement(r,t(l))].concat(n)}},r.prototype.subTransformSequenceExpression=function(e){var n=e.expressions,l=this.subTransform(n[n.length-1]);return l?(1===--n.length&&(e=n[0]),[c.expressionStatement(e)].concat(l)):void 0},r.prototype.subTransformCallExpression=function(e){var n,l,t=e.callee;if(c.isMemberExpression(t,{computed:!1})&&c.isIdentifier(t.property)){switch(t.property.name){case"call":l=c.arrayExpression(e.arguments.slice(1));break;case"apply":l=e.arguments[1]||c.identifier("undefined");break;default:return}n=e.arguments[0],t=t.object}if(c.isIdentifier(t)&&this.scope.bindingIdentifierEquals(t.name,this.ownerId)&&(this.hasTailRecursion=!0,!this.hasDeopt())){var r=[];c.isThisExpression(n)||r.push(c.expressionStatement(c.assignmentExpression("=",this.getThisId(),n||c.identifier("undefined")))),l||(l=c.arrayExpression(e.arguments));var a=this.getArgumentsId(),o=this.getParams();r.push(c.expressionStatement(c.assignmentExpression("=",a,l)));var u,s;if(c.isArrayExpression(l)){var i=l.elements;for(u=0;u<i.length&&u<o.length;u++){s=o[u];var d=i[u]||(i[u]=c.identifier("undefined"));s._isDefaultPlaceholder||(i[u]=c.assignmentExpression("=",s,d))}}else for(this.setsArguments=!0,u=0;u<o.length;u++)s=o[u],s._isDefaultPlaceholder||r.push(c.expressionStatement(c.assignmentExpression("=",s,c.memberExpression(a,c.literal(u),!0))));return r.push(c.expressionStatement(c.assignmentExpression("=",this.getAgainId(),c.literal(!0)))),r.push(c.continueStatement(this.getFunctionId())),r}};var d={enter:function(e,n,l,t){if(c.isIfStatement(e))c.isReturnStatement(e.alternate)&&c.ensureBlock(e,"alternate"),c.isReturnStatement(e.consequent)&&c.ensureBlock(e,"consequent");else{if(c.isReturnStatement(e))return this.skip(),t.subTransform(e.argument);c.isTryStatement(n)?e===n.block?this.skip():n.finalizer&&e!==n.finalizer&&this.skip():c.isFunction(e)?this.skip():c.isVariableDeclaration(e)&&(this.skip(),t.vars.push(e))}}},p={enter:function(e,n,l,t){return c.isThisExpression(e)?(t.needsThis=!0,t.getThisId()):c.isReferencedIdentifier(e,n,{name:"arguments"})?(t.needsArguments=!0,t.getArgumentsId()):c.isFunction(e)&&(this.skip(),c.isFunctionDeclaration(e))?(e=c.variableDeclaration("var",[c.variableDeclarator(e.id,c.toExpression(e))]),e._blockHoist=2,e):void 0}},f={enter:function(e,n,l,t){if(c.isExpressionStatement(e)){var r=e.expression;if(c.isAssignmentExpression(r))if(t.needsThis||r.left!==t.getThisId()){if(!t.needsArguments&&r.left===t.getArgumentsId()&&c.isArrayExpression(r.right))return i(r.right.elements,function(e){return c.expressionStatement(e)})}else this.remove()}}};l.Function=function(e,n,l,t){var a=new r(e,l,t);a.run()}},{"../../../messages":27,"../../../types":117,"../../../util":119,"lodash/array/flatten":188,"lodash/collection/map":197,"lodash/collection/reduceRight":198}],73:[function(e,n,l){"use strict";var t=e("../../../types"),r=function(e,n){return t.binaryExpression("+",e,n)};l.check=function(e){return t.isTemplateLiteral(e)||t.isTaggedTemplateExpression(e)},l.TaggedTemplateExpression=function(e,n,l,r){for(var a=[],o=e.quasi,u=[],s=[],i=0;i<o.quasis.length;i++){var c=o.quasis[i];u.push(t.literal(c.value.cooked)),s.push(t.literal(c.value.raw))}u=t.arrayExpression(u),s=t.arrayExpression(s);var d="tagged-template-literal";return r.isLoose("es6.templateLiterals")&&(d+="-loose"),a.push(t.callExpression(r.addHelper(d),[u,s])),a=a.concat(o.expressions),t.callExpression(e.tag,a)},l.TemplateLiteral=function(e){var n,l=[];for(n=0;n<e.quasis.length;n++){var a=e.quasis[n];l.push(t.literal(a.value.cooked));var o=e.expressions.shift();o&&l.push(o)}if(l.length>1){var u=l[l.length-1];t.isLiteral(u,{value:""})&&l.pop();var s=r(l.shift(),l.shift());for(n=0;n<l.length;n++)s=r(s,l[n]);return s}return l[0]}},{"../../../types":117}],74:[function(e,n,l){"use strict";var t=e("regexpu/rewrite-pattern"),r=e("lodash/array/pull"),a=e("../../../types");l.check=function(e){return a.isLiteral(e)&&e.regex&&e.regex.flags.indexOf("u")>=0},l.Literal=function(e){var n=e.regex;if(n){var l=n.flags.split("");n.flags.indexOf("u")<0||(r(l,"u"),n.pattern=t(n.pattern,n.flags),n.flags=l.join(""))}}},{"../../../types":117,"lodash/array/pull":190,"regexpu/rewrite-pattern":299}],75:[function(e,n,l){"use strict";var t=e("../../../util"),r=e("../../../types");l.experimental=!0;var a=function(e,n,l,t){if(r.isExpressionStatement(e)&&!t.isConsequenceExpressionStatement(e))return n;var a=[];return r.isSequenceExpression(n)?a=n.expressions:a.push(n),a.push(l),r.sequenceExpression(a)};l.AssignmentExpression=function(e,n,l,o){var u=e.left;if(r.isVirtualPropertyExpression(u)){var s,i=e.right;r.isExpressionStatement(n)||(s=l.generateTempBasedOnNode(e.right),s&&(i=s)),"="!==e.operator&&(i=r.binaryExpression(e.operator[0],t.template("abstract-expression-get",{PROPERTY:e.property,OBJECT:e.object}),i));var c=t.template("abstract-expression-set",{PROPERTY:u.property,OBJECT:u.object,VALUE:i});return s&&(c=r.sequenceExpression([r.assignmentExpression("=",s,e.right),c])),a(n,c,i,o)}},l.UnaryExpression=function(e,n,l,o){var u=e.argument;if(r.isVirtualPropertyExpression(u)&&"delete"===e.operator){var s=t.template("abstract-expression-delete",{PROPERTY:u.property,OBJECT:u.object});return a(n,s,r.literal(!0),o)}},l.CallExpression=function(e,n,l){var a=e.callee;if(r.isVirtualPropertyExpression(a)){var o=l.generateTempBasedOnNode(a.object),u=t.template("abstract-expression-call",{PROPERTY:a.property,OBJECT:o||a.object});return u.arguments=u.arguments.concat(e.arguments),o?r.sequenceExpression([r.assignmentExpression("=",o,a.object),u]):u}},l.VirtualPropertyExpression=function(e){return t.template("abstract-expression-get",{PROPERTY:e.property,OBJECT:e.object})},l.PrivateDeclaration=function(e){return r.variableDeclaration("const",e.declarations.map(function(e){return r.variableDeclarator(e,r.newExpression(r.identifier("WeakMap"),[]))}))}},{"../../../types":117,"../../../util":119}],76:[function(e,n,l){"use strict";var t=e("../../helpers/build-comprehension"),r=e("../../../traversal"),a=e("../../../util"),o=e("../../../types");l.experimental=!0,l.ComprehensionExpression=function(e,n,l,t){var r=s;return e.generator&&(r=u),r(e,n,l,t)};var u=function(e){var n=[],l=o.functionExpression(null,[],o.blockStatement(n),!0);return l._aliasFunction=!0,n.push(t(e,function(){return o.expressionStatement(o.yieldExpression(e.body))})),o.callExpression(l,[])},s=function(e,n,l,u){var s=l.generateUidBasedOnNode(n,u),i=a.template("array-comprehension-container",{KEY:s});i.callee._aliasFunction=!0;var c=i.callee.body,d=c.body;r.hasType(e,l,"YieldExpression",o.FUNCTION_TYPES)&&(i.callee.generator=!0,i=o.yieldExpression(i,!0));var p=d.pop();return d.push(t(e,function(){return a.template("array-push",{STATEMENT:e.body,KEY:s},!0)})),d.push(p),i}},{"../../../traversal":112,"../../../types":117,"../../../util":119,"../../helpers/build-comprehension":31}],77:[function(e,n,l){"use strict";l.experimental=!0;var t=e("../../helpers/build-binary-assignment-operator-transformer"),r=e("../../../types"),a=r.memberExpression(r.identifier("Math"),r.identifier("pow"));t(l,{operator:"**",build:function(e,n){return r.callExpression(a,[e,n])}})},{"../../../types":117,"../../helpers/build-binary-assignment-operator-transformer":30}],78:[function(e,n,l){"use strict";var t=e("../../../types");l.experimental=!0,l.manipulateOptions=function(e){e.whitelist.length&&e.whitelist.push("es6.destructuring")};var r=function(e){for(var n=0;n<e.properties.length;n++)if(t.isSpreadProperty(e.properties[n]))return!0;return!1};l.ObjectExpression=function(e,n,l,a){if(r(e)){for(var o=[],u=[],s=function(){u.length&&(o.push(t.objectExpression(u)),u=[])},i=0;i<e.properties.length;i++){var c=e.properties[i];t.isSpreadProperty(c)?(s(),o.push(c.argument)):u.push(c)}return s(),t.isObjectExpression(o[0])||o.unshift(t.objectExpression([])),t.callExpression(a.addHelper("extends"),o)}}},{"../../../types":117}],79:[function(e,n){n.exports={useStrict:e("./other/use-strict"),"spec.functionName":e("./spec/function-name"),"validation.undeclaredVariableCheck":e("./validation/undeclared-variable-check"),"validation.noForInOfAssignment":e("./validation/no-for-in-of-assignment"),"validation.setters":e("./validation/setters"),"validation.react":e("./validation/react"),"spec.blockScopedFunctions":e("./spec/block-scoped-functions"),"playground.malletOperator":e("./playground/mallet-operator"),"playground.methodBinding":e("./playground/method-binding"),"playground.memoizationOperator":e("./playground/memoization-operator"),"playground.objectGetterMemoization":e("./playground/object-getter-memoization"),reactCompat:e("./other/react-compat"),flow:e("./other/flow"),react:e("./other/react"),_modules:e("./internal/modules"),"es7.comprehensions":e("./es7/comprehensions"),"es6.arrowFunctions":e("./es6/arrow-functions"),"es6.classes":e("./es6/classes"),asyncToGenerator:e("./other/async-to-generator"),bluebirdCoroutines:e("./other/bluebird-coroutines"),"es6.objectSuper":e("./es6/object-super"),"es7.objectRestSpread":e("./es7/object-rest-spread"),"es7.exponentiationOperator":e("./es7/exponentiation-operator"),"es6.templateLiterals":e("./es6/template-literals"),"es5.properties.mutators":e("./es5/properties.mutators"),"es6.properties.shorthand":e("./es6/properties.shorthand"),"es6.properties.computed":e("./es6/properties.computed"),"es6.forOf":e("./es6/for-of"),"es6.unicodeRegex":e("./es6/unicode-regex"),"es7.abstractReferences":e("./es7/abstract-references"),"es6.constants":e("./es6/constants"),"es6.parameters.rest":e("./es6/parameters.rest"),"es6.spread":e("./es6/spread"),"es6.parameters.default":e("./es6/parameters.default"),"es6.destructuring":e("./es6/destructuring"),"es6.blockScoping":e("./es6/block-scoping"),"es6.blockScopingTDZ":e("./es6/block-scoping-tdz"),"es6.tailCall":e("./es6/tail-call"),regenerator:e("./other/regenerator"),selfContained:e("./other/self-contained"),"es6.modules":e("./es6/modules"),_blockHoist:e("./internal/block-hoist"),"spec.protoToAssign":e("./spec/proto-to-assign"),_declarations:e("./internal/declarations"),_aliasFunctions:e("./internal/alias-functions"),"spec.typeofSymbol":e("./spec/typeof-symbol"),"spec.undefinedToVoid":e("./spec/undefined-to-void"),_moduleFormatter:e("./internal/module-formatter"),"es3.propertyLiterals":e("./es3/property-literals"),"es3.memberExpressionLiterals":e("./es3/member-expression-literals"),"minification.removeDebugger":e("./minification/remove-debugger"),"minification.removeConsoleCalls":e("./minification/remove-console-calls"),"minification.deadCodeElimination":e("./minification/dead-code-elimination"),"minification.renameLocalVariables":e("./minification/rename-local-variables"),_cleanUp:e("./internal/cleanup")}},{"./es3/member-expression-literals":55,"./es3/property-literals":56,"./es5/properties.mutators":57,"./es6/arrow-functions":58,"./es6/block-scoping":60,"./es6/block-scoping-tdz":59,"./es6/classes":61,"./es6/constants":62,"./es6/destructuring":63,"./es6/for-of":64,"./es6/modules":65,"./es6/object-super":66,"./es6/parameters.default":67,"./es6/parameters.rest":68,"./es6/properties.computed":69,"./es6/properties.shorthand":70,"./es6/spread":71,"./es6/tail-call":72,"./es6/template-literals":73,"./es6/unicode-regex":74,"./es7/abstract-references":75,"./es7/comprehensions":76,"./es7/exponentiation-operator":77,"./es7/object-rest-spread":78,"./internal/alias-functions":80,"./internal/block-hoist":81,"./internal/cleanup":82,"./internal/declarations":83,"./internal/module-formatter":84,"./internal/modules":85,"./minification/dead-code-elimination":86,"./minification/remove-console-calls":87,"./minification/remove-debugger":88,"./minification/rename-local-variables":89,"./other/async-to-generator":90,"./other/bluebird-coroutines":91,"./other/flow":92,"./other/react":94,"./other/react-compat":93,"./other/regenerator":95,"./other/self-contained":96,"./other/use-strict":97,"./playground/mallet-operator":98,"./playground/memoization-operator":99,"./playground/method-binding":100,"./playground/object-getter-memoization":101,"./spec/block-scoped-functions":102,"./spec/function-name":103,"./spec/proto-to-assign":104,"./spec/typeof-symbol":105,"./spec/undefined-to-void":106,"./validation/no-for-in-of-assignment":107,"./validation/react":108,"./validation/setters":109,"./validation/undeclared-variable-check":110}],80:[function(e,n,l){"use strict";var t=e("../../../types"),r={enter:function(e,n,l,r){if(t.isFunction(e)&&!e._aliasFunction)return this.skip();if(e._ignoreAliasFunctions)return this.skip();var a;if(t.isIdentifier(e)&&"arguments"===e.name)a=r.getArgumentsId;else{if(!t.isThisExpression(e))return;a=r.getThisId}return t.isReferenced(e,n)?a():void 0}},a={enter:function(e,n,l,a){return e._aliasFunction?(l.traverse(e,r,a),this.skip()):t.isFunction(e)?this.skip():void 0}},o=function(e,n,l){var r,o,u={getArgumentsId:function(){return r=r||l.generateUidIdentifier("arguments")},getThisId:function(){return o=o||l.generateUidIdentifier("this")}};l.traverse(n,a,u);var s,i=function(n,l){s=s||e(),s.unshift(t.variableDeclaration("var",[t.variableDeclarator(n,l)]))};r&&i(r,t.identifier("arguments")),o&&i(o,t.thisExpression())};l.Program=function(e,n,l){o(function(){return e.body},e,l)},l.FunctionDeclaration=l.FunctionExpression=function(e,n,l){o(function(){return t.ensureBlock(e),e.body.body},e,l)}},{"../../../types":117}],81:[function(e,n,l){"use strict";var t=e("lodash/collection/groupBy"),r=e("lodash/array/flatten"),a=e("lodash/object/values");l.BlockStatement=l.Program={exit:function(e){for(var n=!1,l=0;l<e.body.length;l++){var o=e.body[l];o&&null!=o._blockHoist&&(n=!0)}if(n){var u=t(e.body,function(e){var n=e._blockHoist;return null==n&&(n=1),n===!0&&(n=2),n});e.body=r(a(u).reverse())}}}},{"lodash/array/flatten":188,"lodash/collection/groupBy":195,"lodash/object/values":279}],82:[function(e,n,l){l.SequenceExpression=function(e){return 1===e.expressions.length?e.expressions[0]:void 0}},{}],83:[function(e,n,l){"use strict";var t=e("../../../types");l.secondPass=!0,l.BlockStatement=l.Program=function(e,n,l,r){if(e._declarations){var a,o={};for(var u in e._declarations){var s=e._declarations[u];a=s.kind||"var";var i=t.variableDeclarator(s.id,s.init);s.init?e.body.unshift(r.attachAuxiliaryComment(t.variableDeclaration(a,[i]))):(o[a]=o[a]||[],o[a].push(i))}for(a in o)e.body.unshift(r.attachAuxiliaryComment(t.variableDeclaration(a,o[a])));e._declarations=null}}},{"../../../types":117}],84:[function(e,n,l){"use strict";l.Program=function(e,n,l,t){t.transformers["es6.modules"].canRun()&&(e.body=t.dynamicImports.concat(e.body),t.moduleFormatter.transform&&t.moduleFormatter.transform(e))}},{}],85:[function(e,n,l){"use strict";var t=e("../../../types"),r=function(e,n,l,t){var r=t.opts.resolveModuleSource;e.source&&r&&(e.source.value=r(e.source.value))};l.check=function(e){return t.isImportDeclaration(e)||t.isExportDeclaration(e)},l.ImportDeclaration=r,l.ExportDeclaration=function(e,n,l){r.apply(null,arguments);var a=e.declaration;if(e.default){if(t.isClassDeclaration(a))return e.declaration=a.id,[a,e];if(t.isClassExpression(a)){var o=l.generateUidIdentifier("default");return a=t.variableDeclaration("var",[t.variableDeclarator(o,a)]),e.declaration=o,[a,e]}if(t.isFunctionDeclaration(a))return e._blockHoist=2,e.declaration=a.id,[a,e]}else if(t.isFunctionDeclaration(a))return e.specifiers=[t.importSpecifier(a.id,a.id)],e.declaration=null,e._blockHoist=2,[a,e]}},{"../../../types":117}],86:[function(e,n,l){var t=e("../../../types");l.optional=!0,l.ExpressionStatement=function(e){var n=e.expression;(t.isLiteral(n)||t.isIdentifier(e)&&t.hasBinding(e.name))&&this.remove()},l.IfStatement={exit:function(e){var n=e.consequent,l=e.alternate,r=e.test;return t.isLiteral(r)&&r.value?n:t.isFalsyExpression(r)?l?l:this.remove():(t.isBlockStatement(l)&&!l.body.length&&(l=e.alternate=null),void(t.blockStatement(n)&&!n.body.length&&t.isBlockStatement(l)&&l.body.length&&(e.consequent=e.alternate,e.alternate=null,e.test=t.unaryExpression("!",r,!0))))}}},{"../../../types":117}],87:[function(e,n,l){"use strict";var t=e("../../../types"),r=t.buildMatchMemberExpression("console",!0);l.optional=!0,l.CallExpression=function(e,n){r(e.callee)&&(t.isExpressionStatement(n)?this.parentPath.remove():this.remove())}},{"../../../types":117}],88:[function(e,n,l){var t=e("../../../types");l.optional=!0,l.ExpressionStatement=function(e){t.isIdentifier(e.expression,{name:"debugger"})&&this.remove()}},{"../../../types":117}],89:[function(e,n,l){l.optional=!0,l.Scopable=function(){}},{}],90:[function(e,n,l){"use strict";var t=e("../../helpers/remap-async-to-generator"),r=e("./bluebird-coroutines");l.optional=!0,l.manipulateOptions=r.manipulateOptions,l.Function=function(e,n,l,r){return e.async&&!e.generator?t(e,r.addHelper("async-to-generator"),l):void 0}},{"../../helpers/remap-async-to-generator":38,"./bluebird-coroutines":91}],91:[function(e,n,l){"use strict";var t=e("../../helpers/remap-async-to-generator"),r=e("../../../types");l.manipulateOptions=function(e){e.experimental=!0,e.blacklist.push("regenerator")},l.optional=!0,l.Function=function(e,n,l,a){return e.async&&!e.generator?t(e,r.memberExpression(a.addImport("bluebird",null,!0),r.identifier("coroutine")),l):void 0}},{"../../../types":117,"../../helpers/remap-async-to-generator":38}],92:[function(e,n,l){var t=e("../../../types");l.TypeCastExpression=function(e){return e.expression},l.ImportDeclaration=function(e){e.isType&&this.remove()},l.ExportDeclaration=function(e){t.isTypeAlias(e.declaration)&&this.remove()}},{"../../../types":117}],93:[function(e,n,l){"use strict";var t=e("../../helpers/react"),r=e("../../../types");l.manipulateOptions=function(e){e.blacklist.push("react")},l.optional=!0,e("../../helpers/build-react-transformer")(l,{pre:function(e){e.callee=e.tagExpr},post:function(e){t.isCompatTag(e.tagName)&&(e.call=r.callExpression(r.memberExpression(r.memberExpression(r.identifier("React"),r.identifier("DOM")),e.tagExpr,r.isLiteral(e.tagExpr)),e.args))}})},{"../../../types":117,"../../helpers/build-react-transformer":33,"../../helpers/react":37}],94:[function(e,n,l){"use strict";var t=e("../../helpers/react"),r=e("../../../types"),a=/^\*\s*@jsx\s+([^\s]+)/;l.Program=function(e,n,l,t){var o="React.createElement",u=t.ast.comments[0];if(u){var s=a.exec(u.value);s&&(o=s[1])}t.set("jsxIdentifier",o.split(".").map(r.identifier).reduce(function(e,n){return r.memberExpression(e,n)}))},e("../../helpers/build-react-transformer")(l,{pre:function(e){var n=e.tagName,l=e.args;l.push(t.isCompatTag(n)?r.literal(n):e.tagExpr)},post:function(e,n){e.callee=n.get("jsxIdentifier")}})},{"../../../types":117,"../../helpers/build-react-transformer":33,"../../helpers/react":37}],95:[function(e,n,l){"use strict";var t=e("regenerator-babel"),r=e("../../../types");l.check=function(e){return r.isFunction(e)&&(e.async||e.generator)},l.Program={enter:function(e){t.transform(e),this.stop()}}},{"../../../types":117,"regenerator-babel":291}],96:[function(e,n,l){"use strict";var t=e("lodash/collection/includes"),r=e("../../../util"),a=e("core-js/library"),o=e("lodash/object/has"),u=e("../../../types"),s=u.buildMatchMemberExpression("Symbol.iterator"),i=function(e){return"_"!==e.name&&o(a,e.name)},c=["Symbol","Promise","Map","WeakMap","Set","WeakSet"],d={enter:function(e,n,l,d){var p;if(u.isMemberExpression(e)&&u.isReferenced(e,n)){var f=e.object;if(p=e.property,!u.isReferenced(f,e))return;if(!e.computed&&i(f)&&o(a[f.name],p.name)&&!l.getBindingIdentifier(f.name))return this.skip(),u.prependToMemberExpression(e,d.get("coreIdentifier"))}else{if(u.isReferencedIdentifier(e,n)&&!u.isMemberExpression(n)&&t(c,e.name)&&!l.getBindingIdentifier(e.name))return u.memberExpression(d.get("coreIdentifier"),e);if(u.isCallExpression(e)){var g=e.callee;return e.arguments.length?!1:u.isMemberExpression(g)&&g.computed?(p=g.property,s(p)?r.template("corejs-iterator",{CORE_ID:d.get("coreIdentifier"),VALUE:g.object}):!1):!1}if(u.isBinaryExpression(e)){if("in"!==e.operator)return;var h=e.left;if(!s(h))return;return r.template("corejs-is-iterator",{CORE_ID:d.get("coreIdentifier"),VALUE:e.right})}}}};l.optional=!0,l.manipulateOptions=function(e){e.whitelist.length&&e.whitelist.push("es6.modules")},l.Program=function(e,n,l,t){l.traverse(e,d,t)},l.pre=function(e){e.setDynamic("runtimeIdentifier",function(){return e.addImport("babel-runtime/helpers","babelHelpers")}),e.setDynamic("coreIdentifier",function(){return e.addImport("babel-runtime/core-js","core")}),e.setDynamic("regeneratorIdentifier",function(){return e.addImport("babel-runtime/regenerator","regeneratorRuntime")})},l.Identifier=function(e,n,l,t){return u.isReferencedIdentifier(e,n,{name:"regeneratorRuntime"})?t.get("regeneratorIdentifier"):void 0}},{"../../../types":117,"../../../util":119,"core-js/library":170,"lodash/collection/includes":196,"lodash/object/has":276}],97:[function(e,n,l){"use strict";var t=e("../../../messages"),r=e("../../../types");l.Program=function(e){var n=e.body[0];r.isExpressionStatement(n)&&r.isLiteral(n.expression,{value:"use strict"})&&e.body.shift()},l.post=function(e){e.ast.program.body.unshift(r.expressionStatement(r.literal("use strict")))},l.FunctionDeclaration=l.FunctionExpression=function(){this.skip()},l.ThisExpression=function(){return r.identifier("undefined")},l.CallExpression=function(e,n,l,a){if(r.isIdentifier(e.callee,{name:"eval"}))throw a.errorWithNode(e,t.get("evalInStrictMode"))}},{"../../../messages":27,"../../../types":117}],98:[function(e,n,l){"use strict";var t=e("../../../messages"),r=e("../../helpers/build-conditional-assignment-operator-transformer"),a=e("../../../types");l.playground=!0,r(l,{is:function(e,n){var l=a.isAssignmentExpression(e)&&"||="===e.operator;if(l){var r=e.left;if(!a.isMemberExpression(r)&&!a.isIdentifier(r))throw n.errorWithNode(r,t.get("expectedMemberExpressionOrIdentifier"));return!0}},build:function(e){return a.unaryExpression("!",e,!0)}})},{"../../../messages":27,"../../../types":117,"../../helpers/build-conditional-assignment-operator-transformer":32}],99:[function(e,n,l){"use strict";var t=e("../../helpers/build-conditional-assignment-operator-transformer"),r=e("../../../types");l.playground=!0,t(l,{is:function(e){var n=r.isAssignmentExpression(e)&&"?="===e.operator;return n&&r.assertMemberExpression(e.left),n},build:function(e,n){return r.unaryExpression("!",r.callExpression(r.memberExpression(n.addHelper("has-own"),r.identifier("call")),[e.object,e.property]),!0)}})},{"../../../types":117,"../../helpers/build-conditional-assignment-operator-transformer":32}],100:[function(e,n,l){"use strict";var t=e("../../../types");l.playground=!0,l.BindMemberExpression=function(e,n,l){var r=e.object,a=e.property,o=l.generateTempBasedOnNode(e.object);o&&(r=o);var u=t.callExpression(t.memberExpression(t.memberExpression(r,a),t.identifier("bind")),[r].concat(e.arguments));return o?t.sequenceExpression([t.assignmentExpression("=",o,e.object),u]):u},l.BindFunctionExpression=function(e,n,l){var r=function(n){var r=l.generateUidIdentifier("val");return t.functionExpression(null,[r],t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(r,e.callee),n))]))},a=l.generateTemp("args");return t.sequenceExpression([t.assignmentExpression("=",a,t.arrayExpression(e.arguments)),r(e.arguments.map(function(e,n){return t.memberExpression(a,t.literal(n),!0)}))])}},{"../../../types":117}],101:[function(e,n,l){"use strict";var t=e("../../../types");l.playground=!0;var r={enter:function(e,n,l,r){return t.isFunction(e)?this.skip():void(t.isReturnStatement(e)&&e.argument&&(e.argument=t.memberExpression(t.callExpression(r.file.addHelper("define-property"),[t.thisExpression(),r.key,e.argument]),r.key,!0)))}};l.Property=l.MethodDefinition=function(e,n,l,a){if("memo"===e.kind){e.kind="get";var o=e.value;t.ensureBlock(o);var u=e.key;t.isIdentifier(u)&&!e.computed&&(u=t.literal(u.name));var s={key:u,file:a};return l.traverse(o,r,s),e}}},{"../../../types":117}],102:[function(e,n,l){"use strict";var t=e("../../../types");l.BlockStatement=function(e,n,l,r){if(!(t.isFunction(n)&&n.body===e||t.isExportDeclaration(n)))for(var a=0;a<e.body.length;a++){var o=e.body[a];if(t.isFunctionDeclaration(o)){var u=t.variableDeclaration("let",[t.variableDeclarator(o.id,t.toExpression(o))]);u._blockHoist=2,o.id=null,e.body[a]=u,r.checkNode(u)}}}},{"../../../types":117}],103:[function(e,n,l){"use strict";var t=e("../../../types"),r=e("../../../util"),a={enter:function(e,n,l,r){return t.isReferencedIdentifier(e,n,{name:r.name})&&l.getBindingIdentifier(e.name)===r.binding?r.getOuter():void 0}};l.FunctionExpression=function(e,n,l){if(!e.id){var o;if(t.isProperty(n)&&"init"===n.kind&&!n.computed)o=n.key;else{if(!t.isVariableDeclarator(n))return;o=n.id}if(t.isIdentifier(o)){var u=t.toIdentifier(o.name);o=t.identifier(u);var s=l.getOwnBindingInfo(u);if(s)return void("param"===s.type||(e.id=o));var i,c=l.getBindingIdentifier(u);return l.traverse(e,a,{name:u,binding:c,getOuter:function(){return t.callExpression(i||(i=l.generateUidIdentifier("getOuter")),[])}}),e.id=o,i?r.template("named-func",{GET_OUTER_ID:i,FUNCTION:e,ID:o}):void 0}}}},{"../../../types":117,"../../../util":119}],104:[function(e,n,l){"use strict";var t=e("../../../types"),r=e("lodash/array/pull"),a=function(e){return t.isLiteral(t.toComputedKey(e,e.key),{value:"__proto__"})},o=function(e){var n=e.left;return t.isMemberExpression(n)&&t.isLiteral(t.toComputedKey(n,n.property),{value:"__proto__"})},u=function(e,n,l){return t.expressionStatement(t.callExpression(l.addHelper("defaults"),[n,e.right]))
};l.optional=!0,l.secondPass=!0,l.AssignmentExpression=function(e,n,l,r){if(o(e)){var a=[],s=e.left.object,i=l.generateTempBasedOnNode(e.left.object);return a.push(t.expressionStatement(t.assignmentExpression("=",i,s))),a.push(u(e,i,r)),i&&a.push(i),t.toSequenceExpression(a)}},l.ExpressionStatement=function(e,n,l,r){var a=e.expression;if(t.isAssignmentExpression(a,{operator:"="}))return o(a)?u(a,a.left.object,r):void 0},l.ObjectExpression=function(e,n,l,o){for(var u,s=0;s<e.properties.length;s++){var i=e.properties[s];a(i)&&(u=i.value,r(e.properties,i))}if(u){var c=[t.objectExpression([]),u];return e.properties.length&&c.push(e),t.callExpression(o.addHelper("extends"),c)}}},{"../../../types":117,"lodash/array/pull":190}],105:[function(e,n,l){"use strict";var t=e("../../../types");l.optional=!0,l.UnaryExpression=function(e,n,l,r){if(this.skip(),"typeof"===e.operator){var a=t.callExpression(r.addHelper("typeof"),[e.argument]);if(t.isIdentifier(e.argument)){var o=t.literal("undefined");return t.conditionalExpression(t.binaryExpression("===",t.unaryExpression("typeof",e.argument),o),o,a)}return a}}},{"../../../types":117}],106:[function(e,n,l){"use strict";var t=e("../../../types");l.optional=!0,l.Identifier=function(e,n){return"undefined"===e.name&&t.isReferenced(e,n)?t.unaryExpression("void",t.literal(0),!0):void 0}},{"../../../types":117}],107:[function(e,n,l){"use strict";var t=e("../../../messages"),r=e("../../../types");l.check=r.isFor,l.ForInStatement=l.ForOfStatement=function(e,n,l,a){var o=e.left;if(r.isVariableDeclaration(o)){var u=o.declarations[0];if(u.init)throw a.errorWithNode(u,t.get("noAssignmentsInForHead"))}}},{"../../../messages":27,"../../../types":117}],108:[function(e,n,l){var t=e("../../../messages"),r=e("../../../types"),a=function(e,n){if(r.isLiteral(e)){var l=e.value,a=l.toLowerCase();if("react"===a&&l!==a)throw n.errorWithNode(e,t.get("didYouMean","react"))}};l.CallExpression=function(e,n,l,t){r.isIdentifier(e.callee,{name:"require"})&&1===e.arguments.length&&a(e.arguments[0],t)},l.ImportDeclaration=l.ExportDeclaration=function(e,n,l,t){a(e.source,t)}},{"../../../messages":27,"../../../types":117}],109:[function(e,n,l){"use strict";var t=e("../../../messages");l.check=function(e){return"set"===e.kind},l.MethodDefinition=l.Property=function(e,n,l,r){if("set"===e.kind&&1!==e.value.params.length)throw r.errorWithNode(e.value,t.get("settersInvalidParamLength"))}},{"../../../messages":27}],110:[function(e,n,l){"use strict";var t=e("leven"),r=e("../../../messages"),a=e("../../../types");l.optional=!0,l.Identifier=function(e,n,l,o){if(a.isReferenced(e,n)&&!l.hasBinding(e.name)){var u,s=l.getAllBindings(),i=-1;for(var c in s){var d=t(e.name,c);0>=d||d>3||i>=d||(u=c,i=d)}var p;throw p=u?r.get("undeclaredVariableSuggestion",e.name,u):r.get("undeclaredVariable",e.name),o.errorWithNode(e,p,ReferenceError)}}},{"../../../messages":27,"../../../types":117,leven:186}],111:[function(e,n){"use strict";function l(e,n,l,t){this.shouldFlatten=!1,this.parentPath=t,this.scope=e,this.state=l,this.opts=n}n.exports=l;var t=e("./path"),r=e("lodash/array/flatten"),a=e("lodash/array/compact");l.prototype.flatten=function(){this.shouldFlatten=!0},l.prototype.visitNode=function(e,n,l){var r=new t(this,e,n,l);return r.visit()},l.prototype.visit=function(e,n){var l=e[n];if(l){if(!Array.isArray(l))return this.visitNode(e,e,n);if(0!==l.length){for(var t=0;t<l.length;t++)if(l[t]&&this.visitNode(e,l,t))return!0;this.shouldFlatten&&(e[n]=r(e[n]),"body"===n&&(e[n]=a(e[n])))}}}},{"./path":113,"lodash/array/compact":187,"lodash/array/flatten":188}],112:[function(e,n){"use strict";function l(e,n,t,r){if(e){if(!n.noScope&&!t&&"Program"!==e.type&&"File"!==e.type)throw new Error("Must pass a scope unless traversing a Program/File got a "+e.type+" node");if(n||(n={}),n.enter||(n.enter=function(){}),n.exit||(n.exit=function(){}),Array.isArray(e))for(var a=0;a<e.length;a++)l.node(e[a],n,t,r);else l.node(e,n,t,r)}}function t(e){e._declarations=null,e.extendedRange=null,e._scopeInfo=null,e.tokens=null,e.range=null,e.start=null,e.end=null,e.loc=null,e.raw=null,Array.isArray(e.trailingComments)&&r(e.trailingComments),Array.isArray(e.leadingComments)&&r(e.leadingComments)}function r(e){for(var n=0;n<e.length;n++)t(e[n])}function a(e,n,l,t){e.type===t.type&&(t.has=!0,this.skip())}n.exports=l;var o=e("./context"),u=e("lodash/collection/includes"),s=e("../types");l.node=function(e,n,l,t,r){var a=s.VISITOR_KEYS[e.type];if(a)for(var u=new o(l,n,t,r),i=0;i<a.length;i++)if(u.visit(e,a[i]))return};var i={noScope:!0,enter:t};l.removeProperties=function(e){return t(e),l(e,i),e},l.explode=function(e){for(var n in e){var l=e[n],t=s.FLIPPED_ALIAS_KEYS[n];if(t)for(var r=0;r<t.length;r++)e[t[r]]=l}return e},l.hasType=function(e,n,t,r){if(u(r,e.type))return!1;if(e.type===t)return!0;var o={has:!1,type:t};return l(e,{blacklist:r,enter:a},n,o),o.has}},{"../types":117,"./context":111,"lodash/collection/includes":196}],113:[function(e,n){"use strict";function l(e,n,t,r){this.shouldRemove=!1,this.shouldSkip=!1,this.shouldStop=!1,this.parentPath=e.parentPath,this.context=e,this.state=this.context.state,this.opts=this.context.opts,this.key=r,this.obj=t,this.parent=n,this.scope=l.getScope(this.getNode(),n,e.scope),this.state=e.state}n.exports=l;var t=e("./index"),r=e("lodash/collection/includes"),a=e("./scope"),o=e("../types");l.prototype.remove=function(){this.shouldRemove=!0,this.shouldSkip=!0},l.prototype.skip=function(){this.shouldSkip=!0},l.prototype.stop=function(){this.shouldStop=!0,this.shouldSkip=!0},l.prototype.flatten=function(){this.context.flatten()},l.getScope=function(e,n,l){var t=l;return o.isScope(e,n)&&(t=new a(e,n,l)),t},l.prototype.maybeRemove=function(){this.shouldRemove&&(this.setNode(null),this.flatten())},l.prototype.setNode=function(e){return this.obj[this.key]=e},l.prototype.getNode=function(){return this.obj[this.key]},l.prototype.replaceNode=function(e){var n=Array.isArray(e),l=e;n&&(l=e[0]),l&&o.inheritsComments(l,this.getNode()),this.setNode(e);var t=this.scope&&this.scope.file;if(t)if(n)for(var a=0;a<e.length;a++)t.checkNode(e[a],this.scope);else t.checkNode(e,this.scope);n&&(r(o.STATEMENT_OR_BLOCK_KEYS,this.key)&&!o.isBlockStatement(this.obj)&&o.ensureBlock(this.obj,this.key),this.flatten())},l.prototype.call=function(e){var n=this.getNode();if(n){var l=this.opts,t=l[e]||l;l[n.type]&&(t=l[n.type][e]||t);var r=t.call(this,n,this.parent,this.scope,this.state);return r&&(this.replaceNode(r),n=r),this.maybeRemove(),n}},l.prototype.visit=function(){var e=this.opts,n=this.getNode();if(!(e.blacklist&&e.blacklist.indexOf(n.type)>-1)){if(this.call("enter"),this.shouldSkip)return this.shouldStop;if(n=this.getNode(),Array.isArray(n))for(var l=0;l<n.length;l++)t.node(n[l],e,this.scope,this.state,this);else t.node(n,e,this.scope,this.state,this),this.call("exit");return this.shouldStop}}},{"../types":117,"./index":112,"./scope":114,"lodash/collection/includes":196}],114:[function(e,n){"use strict";function l(e,n,l,t){this.parent=l,this.file=l?l.file:t,this.parentBlock=n,this.block=e,this.crawl()}n.exports=l;var t=e("lodash/collection/includes"),r=e("./index"),a=e("lodash/object/defaults"),o=e("../messages"),u=e("globals"),s=e("lodash/array/flatten"),i=e("lodash/object/extend"),c=e("../helpers/object"),d=e("lodash/collection/each"),p=e("../types");l.globals=s([u.builtin,u.browser,u.node].map(Object.keys)),l.prototype.traverse=function(e,n,l){r(e,n,this,l)},l.prototype.generateTemp=function(e){var n=this.generateUidIdentifier(e||"temp");return this.push({key:n.name,id:n}),n},l.prototype.generateUidIdentifier=function(e){var n=p.identifier(this.generateUid(e));return this.getFunctionParent().registerBinding("uid",n),n},l.prototype.generateUid=function(e){e=p.toIdentifier(e).replace(/^_+/,"");var n,l=0;do n=this._generateUid(e,l),l++;while(this.hasBinding(n)||this.hasGlobal(n));return n},l.prototype._generateUid=function(e,n){var l=e;return n>1&&(l+=n),"_"+l},l.prototype.generateUidBasedOnNode=function(e){var n=e;p.isAssignmentExpression(e)?n=e.left:p.isVariableDeclarator(e)?n=e.id:p.isProperty(n)&&(n=n.key);var l=[],t=function(e){p.isMemberExpression(e)?(t(e.object),t(e.property)):p.isIdentifier(e)?l.push(e.name):p.isLiteral(e)?l.push(e.value):p.isCallExpression(e)&&t(e.callee)};t(n);var r=l.join("$");return r=r.replace(/^_/,"")||"ref",this.generateUidIdentifier(r)},l.prototype.generateTempBasedOnNode=function(e){if(p.isIdentifier(e)&&this.hasBinding(e.name))return null;var n=this.generateUidBasedOnNode(e);return this.push({key:n.name,id:n}),n},l.prototype.checkBlockScopedCollisions=function(e,n,l){var t=this.getOwnBindingInfo(n);if(t&&"param"!==e&&!("hoisted"===e&&"let"===t.kind||"let"!==t.kind&&"const"!==t.kind&&"module"!==t.kind))throw this.file.errorWithNode(l,o.get("scopeDuplicateDeclaration",n),TypeError)},l.prototype.rename=function(e,n){n=n||this.generateUidIdentifier(e).name;var l=this.getBindingInfo(e);if(l){var t=l.identifier,r=l.scope;r.traverse(r.block,{enter:function(l,r,a){if(p.isReferencedIdentifier(l,r)&&l.name===e)l.name=n;else if(p.isDeclaration(l)){var o=p.getBindingIdentifiers(l);for(var u in o)u===e&&(o[u].name=n)}else p.isScope(l,r)&&(a.bindingIdentifierEquals(e,t)||this.skip())}}),this.clearOwnBinding(e),r.bindings[n]=l,t.name=n}},l.prototype.inferType=function(e){var n;if(p.isVariableDeclarator(e)&&(n=e.init),p.isArrayExpression(n))return p.genericTypeAnnotation(p.identifier("Array"));if(!p.isObjectExpression(n)&&!p.isLiteral(n)){if(p.isCallExpression(n)&&p.isIdentifier(n.callee)){var l=this.getBindingInfo(n.callee.name);if(l){var t=l.node;return!l.reassigned&&p.isFunction(t)&&e.returnType}}p.isIdentifier(n)}},l.prototype.isTypeGeneric=function(e,n){var l=this.getBindingInfo(e);if(!l)return!1;var t=l.typeAnnotation;return p.isGenericTypeAnnotation(t)&&p.isIdentifier(t.id,{name:n})},l.prototype.assignTypeGeneric=function(e,n){this.assignType(e,p.genericTypeAnnotation(p.identifier(n)))},l.prototype.assignType=function(e,n){var l=this.getBindingInfo(e);l&&(l.identifier.typeAnnotation=l.typeAnnotation=n)},l.prototype.getTypeAnnotation=function(e,n,l){var t,r={annotation:null,inferred:!1};return n.typeAnnotation&&(t=n.typeAnnotation),t||(r.inferred=!0,t=this.inferType(l)),t&&(p.isTypeAnnotation(t)&&(t=t.typeAnnotation),r.annotation=t),r},l.prototype.toArray=function(e,n){var l=this.file;if(p.isIdentifier(e)&&this.isTypeGeneric(e.name,"Array"))return e;if(p.isArrayExpression(e))return e;if(p.isIdentifier(e,{name:"arguments"}))return p.callExpression(p.memberExpression(l.addHelper("slice"),p.identifier("call")),[e]);var t="to-array",r=[e];return n===!0?t="to-consumable-array":n&&(r.push(p.literal(n)),t="sliced-to-array"),p.callExpression(l.addHelper(t),r)},l.prototype.clearOwnBinding=function(e){delete this.bindings[e]},l.prototype.registerDeclaration=function(e){if(p.isFunctionDeclaration(e))this.registerBinding("hoisted",e);else if(p.isVariableDeclaration(e))for(var n=0;n<e.declarations.length;n++)this.registerBinding(e.kind,e.declarations[n]);else p.isClassDeclaration(e)?this.registerBinding("let",e):p.isImportDeclaration(e)||p.isExportDeclaration(e)?this.registerBinding("module",e):this.registerBinding("unknown",e)},l.prototype.registerBindingReassignment=function(e){var n=p.getBindingIdentifiers(e);for(var l in n){var t=this.getBindingInfo(l);t&&(t.reassigned=!0,t.typeAnnotationInferred&&(t.typeAnnotation=null))}},l.prototype.registerBinding=function(e,n){if(!e)throw new ReferenceError("no `kind`");var l=p.getBindingIdentifiers(n);for(var t in l){var r=l[t];this.checkBlockScopedCollisions(e,t,r);var a=this.getTypeAnnotation(t,r,n);this.bindings[t]={typeAnnotationInferred:a.inferred,typeAnnotation:a.annotation,reassigned:!1,identifier:r,scope:this,node:n,kind:e}}},l.prototype.registerVariableDeclaration=function(e){for(var n=e.declarations,l=0;l<n.length;l++)this.registerBinding(n[l],e.kind)};var f={enter:function(e,n,l,t){return p.isFor(e)&&d(p.FOR_INIT_KEYS,function(n){var l=e[n];p.isVar(l)&&t.scope.registerBinding("var",l)}),p.isFunction(e)?this.skip():void(t.blockId&&e===t.blockId||p.isBlockScoped(e)||p.isExportDeclaration(e)&&p.isDeclaration(e.declaration)||p.isDeclaration(e)&&t.scope.registerDeclaration(e))}};l.prototype.addGlobal=function(e){this.globals[e.name]=e},l.prototype.hasGlobal=function(e){var n=this;do if(n.globals[e])return!0;while(n=n.parent);return!1};var g={enter:function(e,n,l,t){p.isReferencedIdentifier(e,n)&&!l.hasBinding(e.name)?t.addGlobal(e):p.isLabeledStatement(e)?t.addGlobal(e):(p.isAssignmentExpression(e)||p.isUpdateExpression(e)||p.isUnaryExpression(e)&&"delete"===e.operator)&&l.registerBindingReassignment(e)}},h={enter:function(e,n,l,t){p.isFunctionDeclaration(e)||p.isBlockScoped(e)?t.registerDeclaration(e):p.isScope(e,n)&&this.skip()}};l.prototype.crawl=function(){var e,n=this.block,l=n._scopeInfo;if(l)return void i(this,l);if(l=n._scopeInfo={bindings:c(),globals:c()},i(this,l),p.isLoop(n)){for(e=0;e<p.FOR_INIT_KEYS.length;e++){var t=n[p.FOR_INIT_KEYS[e]];p.isBlockScoped(t)&&this.registerBinding("let",t)}p.isBlockStatement(n.body)&&(n=n.body)}if(p.isFunctionExpression(n)&&n.id&&(p.isProperty(this.parentBlock,{method:!0})||this.registerBinding("var",n.id)),p.isFunction(n)){for(e=0;e<n.params.length;e++)this.registerBinding("param",n.params[e]);this.traverse(n.body,h,this)}(p.isBlockStatement(n)||p.isProgram(n))&&this.traverse(n,h,this),p.isCatchClause(n)&&this.registerBinding("let",n.param),p.isComprehensionExpression(n)&&this.registerBinding("let",n),(p.isProgram(n)||p.isFunction(n))&&this.traverse(n,f,{blockId:n.id,scope:this}),p.isProgram(n)&&this.traverse(n,g,this)},l.prototype.push=function(e){var n=this.block;if((p.isLoop(n)||p.isCatchClause(n)||p.isFunction(n))&&(p.ensureBlock(n),n=n.body),!p.isBlockStatement(n)&&!p.isProgram(n))throw new TypeError("cannot add a declaration here in node type "+n.type);n._declarations=n._declarations||{},n._declarations[e.key]={kind:e.kind,id:e.id,init:e.init}},l.prototype.getFunctionParent=function(){for(var e=this;e.parent&&!p.isFunction(e.block);)e=e.parent;return e},l.prototype.getAllBindings=function(){var e=c(),n=this;do a(e,n.bindings),n=n.parent;while(n);return e},l.prototype.getAllBindingsOfKind=function(e){var n=c(),l=this;do{for(var t in l.bindings){var r=l.bindings[t];r.kind===e&&(n[t]=r)}l=l.parent}while(l);return n},l.prototype.bindingIdentifierEquals=function(e,n){return this.getBindingIdentifier(e)===n},l.prototype.getBindingInfo=function(e){var n=this;do{var l=n.getOwnBindingInfo(e);if(l)return l}while(n=n.parent)},l.prototype.getOwnBindingInfo=function(e){return this.bindings[e]},l.prototype.getBindingIdentifier=function(e){var n=this.getBindingInfo(e);return n&&n.identifier},l.prototype.getOwnBindingIdentifier=function(e){var n=this.bindings[e];return n&&n.identifier},l.prototype.hasOwnBinding=function(e){return!!this.getOwnBindingInfo(e)},l.prototype.hasBinding=function(e){return e?this.hasOwnBinding(e)?!0:this.parentHasBinding(e)?!0:t(l.globals,e)?!0:!1:!1},l.prototype.parentHasBinding=function(e){return this.parent&&this.parent.hasBinding(e)}},{"../helpers/object":24,"../messages":27,"../types":117,"./index":112,globals:181,"lodash/array/flatten":188,"lodash/collection/each":193,"lodash/collection/includes":196,"lodash/object/defaults":274,"lodash/object/extend":275}],115:[function(e,n){n.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While","Scopable"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While","Scopable"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],PrivateDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scopable","Function","Expression"],FunctionDeclaration:["Scopable","Function","Statement","Declaration"],FunctionExpression:["Scopable","Function","Expression"],ImportSpecifier:["ModuleSpecifier"],ExportSpecifier:["ModuleSpecifier"],BlockStatement:["Statement","Scopable"],Program:["Scopable"],CatchClause:["Scopable"],LogicalExpression:["Binary","Expression"],BinaryExpression:["Binary","Expression"],UnaryExpression:["UnaryLike","Expression"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class","Expression"],ForOfStatement:["Scopable","Statement","For","Loop"],ForInStatement:["Scopable","Statement","For","Loop"],ForStatement:["Scopable","Statement","For","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],AssignmentPattern:["Pattern"],Property:["UserWhitespacable"],JSXElement:["UserWhitespacable","Expression"],ArrayExpression:["Expression"],AssignmentExpression:["Expression"],AwaitExpression:["Expression"],BindFunctionExpression:["Expression"],BindMemberExpression:["Expression"],CallExpression:["Expression"],ComprehensionExpression:["Expression","Scopable"],ConditionalExpression:["Expression"],Identifier:["Expression"],Literal:["Expression"],MemberExpression:["Expression"],NewExpression:["Expression"],ObjectExpression:["Expression"],SequenceExpression:["Expression"],TaggedTemplateExpression:["Expression"],ThisExpression:["Expression"],UpdateExpression:["Expression"],VirtualPropertyExpression:["Expression"],JSXEmptyExpression:["Expression"],JSXMemberExpression:["Expression"],YieldExpression:["Expression"],JSXAttribute:["JSX"],JSXClosingElement:["JSX"],JSXElement:["JSX"],JSXEmptyExpression:["JSX"],JSXExpressionContainer:["JSX"],JSXIdentifier:["JSX"],JSXMemberExpression:["JSX"],JSXNamespacedName:["JSX"],JSXOpeningElement:["JSX"],JSXSpreadAttribute:["JSX"]}},{}],116:[function(e,n){n.exports={ArrayExpression:{elements:null},ArrowFunctionExpression:{params:null,body:null},AssignmentExpression:{operator:null,left:null,right:null},BinaryExpression:{operator:null,left:null,right:null},BlockStatement:{body:null},CallExpression:{callee:null,arguments:null},ConditionalExpression:{test:null,consequent:null,alternate:null},ExpressionStatement:{expression:null},File:{program:null,comments:null,tokens:null},FunctionExpression:{id:null,params:null,body:null,generator:!1},FunctionDeclaration:{id:null,params:null,body:null,generator:!1},GenericTypeAnnotation:{id:null,typeParameters:null},Identifier:{name:null},IfStatement:{test:null,consequent:null,alternate:null},ImportDeclaration:{specifiers:null,source:null},ImportSpecifier:{id:null,name:null},Literal:{value:null},LogicalExpression:{operator:null,left:null,right:null},MemberExpression:{object:null,property:null,computed:!1},MethodDefinition:{key:null,value:null,computed:!1,"static":!1,kind:null},NewExpression:{callee:null,arguments:null},ObjectExpression:{properties:null},Program:{body:null},Property:{kind:null,key:null,value:null,computed:!1},ReturnStatement:{argument:null},SequenceExpression:{expressions:null},ThrowExpression:{argument:null},UnaryExpression:{operator:null,argument:null,prefix:null},VariableDeclaration:{kind:null,declarations:null},VariableDeclarator:{id:null,init:null},WithStatement:{object:null,body:null},YieldExpression:{argument:null,delegate:null}}},{}],117:[function(e,n,l){"use strict";function t(e,n){var l=d["is"+e]=function(l,t){return d.is(e,l,t,n)};d["assert"+e]=function(n,t){if(t=t||{},!l(n,t))throw new Error("Expected type "+JSON.stringify(e)+" with option "+JSON.stringify(t))}}var r=e("../helpers/to-fast-properties"),a=e("lodash/lang/isString"),o=e("lodash/array/compact"),u=e("esutils"),s=e("../helpers/object"),i=e("lodash/collection/each"),c=e("lodash/array/uniq"),d=l;d.STATEMENT_OR_BLOCK_KEYS=["consequent","body"],d.NATIVE_TYPE_NAMES=["Array","Object","Number","Boolean","Date","Array","String"],d.FOR_INIT_KEYS=["left","init"],d.VISITOR_KEYS=e("./visitor-keys"),d.ALIAS_KEYS=e("./alias-keys"),d.FLIPPED_ALIAS_KEYS={},i(d.VISITOR_KEYS,function(e,n){t(n,!0)}),i(d.ALIAS_KEYS,function(e,n){i(e,function(e){var l=d.FLIPPED_ALIAS_KEYS[e]=d.FLIPPED_ALIAS_KEYS[e]||[];l.push(n)})}),i(d.FLIPPED_ALIAS_KEYS,function(e,n){d[n.toUpperCase()+"_TYPES"]=e,t(n,!1)}),d.is=function(e,n,l,t){if(!n)return!1;var r=e===n.type;if(!r&&!t){var a=d.FLIPPED_ALIAS_KEYS[e];"undefined"!=typeof a&&(r=a.indexOf(n.type)>-1)}return r?"undefined"!=typeof l?d.shallowEqual(n,l):!0:!1},d.BUILDER_KEYS=e("./builder-keys"),i(d.VISITOR_KEYS,function(e,n){if(!d.BUILDER_KEYS[n]){var l={};i(e,function(e){l[e]=null}),d.BUILDER_KEYS[n]=l}}),i(d.BUILDER_KEYS,function(e,n){d[n[0].toLowerCase()+n.slice(1)]=function(){var l={};l.start=null,l.type=n;var t=0;for(var r in e){var a=arguments[t++];void 0===a&&(a=e[r]),l[r]=a}return l}}),d.toComputedKey=function(e,n){return e.computed||d.isIdentifier(n)&&(n=d.literal(n.name)),n},d.isFalsyExpression=function(e){return d.isLiteral(e)?!e.value:d.isIdentifier(e)?"undefined"===e.name:!1},d.toSequenceExpression=function(e,n){var l=[];return i(e,function(e){d.isExpression(e)&&l.push(e),d.isExpressionStatement(e)?l.push(e.expression):d.isVariableDeclaration(e)&&i(e.declarations,function(t){n.push({kind:e.kind,key:t.id.name,id:t.id}),l.push(d.assignmentExpression("=",t.id,t.init))})}),1===l.length?l[0]:d.sequenceExpression(l)},d.shallowEqual=function(e,n){for(var l=Object.keys(n),t=0;t<l.length;t++){var r=l[t];if(e[r]!==n[r])return!1}return!0},d.appendToMemberExpression=function(e,n,l){return e.object=d.memberExpression(e.object,e.property,e.computed),e.property=n,e.computed=!!l,e},d.prependToMemberExpression=function(e,n){return e.object=d.memberExpression(n,e.object),e},d.isReferenced=function(e,n){if(d.isMemberExpression(n))return n.property===e&&n.computed?!0:n.object===e?!0:!1;if(d.isProperty(n)&&n.key===e)return n.computed;if(d.isVariableDeclarator(n))return n.id!==e;if(d.isFunction(n)){for(var l=0;l<n.params.length;l++){var t=n.params[l];if(t===e)return!1}return n.id!==e}return d.isClass(n)?n.id!==e:d.isMethodDefinition(n)?n.key===e&&n.computed:d.isLabeledStatement(n)?!1:d.isCatchClause(n)?n.param!==e:d.isRestElement(n)?!1:d.isAssignmentPattern(n)?n.right===e:d.isPattern(n)?!1:d.isImportSpecifier(n)?!1:d.isImportBatchSpecifier(n)?!1:d.isPrivateDeclaration(n)?!1:!0},d.isReferencedIdentifier=function(e,n,l){return d.isIdentifier(e,l)&&d.isReferenced(e,n)},d.isValidIdentifier=function(e){return a(e)&&u.keyword.isIdentifierName(e)&&!u.keyword.isReservedWordES6(e,!0)},d.toIdentifier=function(e){return d.isIdentifier(e)?e.name:(e+="",e=e.replace(/[^a-zA-Z0-9$_]/g,"-"),e=e.replace(/^[-0-9]+/,""),e=e.replace(/[-\s]+(.)?/g,function(e,n){return n?n.toUpperCase():""}),d.isValidIdentifier(e)||(e="_"+e),e||"_")},d.ensureBlock=function(e,n){return n=n||"body",e[n]=d.toBlock(e[n],e)},d.buildMatchMemberExpression=function(e,n){var l=e.split(".");return function(e){if(!d.isMemberExpression(e))return!1;for(var t=[e],r=0;t.length;){var a=t.shift();if(n&&r===l.length)return!0;if(d.isIdentifier(a)){if(l[r]!==a.name)return!1}else{if(!d.isLiteral(a)){if(d.isMemberExpression(a)){if(a.computed&&!d.isLiteral(a.property))return!1;t.push(a.object),t.push(a.property);continue}return!1}if(l[r]!==a.value)return!1}if(++r>l.length)return!1}return!0}},d.toStatement=function(e,n){if(d.isStatement(e))return e;var l,t=!1;if(d.isClass(e))t=!0,l="ClassDeclaration";else if(d.isFunction(e))t=!0,l="FunctionDeclaration";else if(d.isAssignmentExpression(e))return d.expressionStatement(e);if(t&&!e.id&&(l=!1),!l){if(n)return!1;throw new Error("cannot turn "+e.type+" to a statement")}return e.type=l,e},l.toExpression=function(e){if(d.isExpressionStatement(e)&&(e=e.expression),d.isClass(e)?e.type="ClassExpression":d.isFunction(e)&&(e.type="FunctionExpression"),d.isExpression(e))return e;throw new Error("cannot turn "+e.type+" to an expression")},d.toBlock=function(e,n){return d.isBlockStatement(e)?e:(d.isEmptyStatement(e)&&(e=[]),Array.isArray(e)||(d.isStatement(e)||(e=d.isFunction(n)?d.returnStatement(e):d.expressionStatement(e)),e=[e]),d.blockStatement(e))},d.getBindingIdentifiers=function(e){for(var n=[].concat(e),l=s();n.length;){var t=n.shift();if(t){var r=d.getBindingIdentifiers.keys[t.type];if(d.isIdentifier(t))l[t.name]=t;else if(d.isImportSpecifier(t))n.push(t.name||t.id);else if(d.isExportDeclaration(t))d.isDeclaration(e.declaration)&&n.push(e.declaration);else if(r)for(var a=0;a<r.length;a++){var o=r[a];n=n.concat(t[o]||[])}}}return l},d.getBindingIdentifiers.keys={UnaryExpression:["argument"],AssignmentExpression:["left"],ImportBatchSpecifier:["name"],VariableDeclarator:["id"],FunctionDeclaration:["id"],ClassDeclaration:["id"],SpreadElement:["argument"],RestElement:["argument"],UpdateExpression:["argument"],SpreadProperty:["argument"],Property:["value"],ComprehensionBlock:["left"],AssignmentPattern:["left"],PrivateDeclaration:["declarations"],ComprehensionExpression:["blocks"],ImportDeclaration:["specifiers"],VariableDeclaration:["declarations"],ArrayPattern:["elements"],ObjectPattern:["properties"]},d.isLet=function(e){return d.isVariableDeclaration(e)&&("var"!==e.kind||e._let)},d.isBlockScoped=function(e){return d.isFunctionDeclaration(e)||d.isClassDeclaration(e)||d.isLet(e)},d.isVar=function(e){return d.isVariableDeclaration(e,{kind:"var"})&&!e._let},d.COMMENT_KEYS=["leadingComments","trailingComments"],d.removeComments=function(e){return i(d.COMMENT_KEYS,function(n){delete e[n]}),e},d.inheritsComments=function(e,n){return i(d.COMMENT_KEYS,function(l){e[l]=c(o([].concat(e[l],n[l])))}),e},d.inherits=function(e,n){return e._declarations=n._declarations,e._scopeInfo=n._scopeInfo,e.range=n.range,e.start=n.start,e.loc=n.loc,e.end=n.end,d.inheritsComments(e,n),e},d.getLastStatements=function(e){var n=[],l=function(e){n=n.concat(d.getLastStatements(e))};return d.isIfStatement(e)?(l(e.consequent),l(e.alternate)):d.isFor(e)||d.isWhile(e)?l(e.body):d.isProgram(e)||d.isBlockStatement(e)?l(e.body[e.body.length-1]):e&&n.push(e),n},d.getSpecifierName=function(e){return e.name||e.id},d.getSpecifierId=function(e){return e.default?d.identifier("default"):e.id},d.isSpecifierDefault=function(e){return e.default||d.isIdentifier(e.id)&&"default"===e.id.name},d.isScope=function(e,n){if(d.isBlockStatement(e)){if(d.isLoop(n.block,{body:e}))return!1;if(d.isFunction(n.block,{body:e}))return!1}return d.isScopable(e)},r(d),r(d.VISITOR_KEYS)},{"../helpers/object":24,"../helpers/to-fast-properties":26,"./alias-keys":115,"./builder-keys":116,"./visitor-keys":118,esutils:179,"lodash/array/compact":187,"lodash/array/uniq":191,"lodash/collection/each":193,"lodash/lang/isString":271}],118:[function(e,n){n.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindFunctionExpression:["callee","arguments"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateDeclaration:["declarations"],Program:["body"],Property:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],AnyTypeAnnotation:[],ArrayTypeAnnotation:[],BooleanTypeAnnotation:[],ClassProperty:["key","value"],DeclareClass:[],DeclareFunction:[],DeclareModule:[],DeclareVariable:[],FunctionTypeAnnotation:[],FunctionTypeParam:[],GenericTypeAnnotation:[],InterfaceExtends:[],InterfaceDeclaration:[],IntersectionTypeAnnotation:[],NullableTypeAnnotation:[],NumberTypeAnnotation:[],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],TupleTypeAnnotation:[],TypeofTypeAnnotation:[],TypeAlias:[],TypeAnnotation:[],TypeCastExpression:["expression"],TypeParameterDeclaration:[],TypeParameterInstantiation:[],ObjectTypeAnnotation:[],ObjectTypeCallProperty:[],ObjectTypeIndexer:[],ObjectTypeProperty:[],QualifiedTypeIdentifier:[],UnionTypeAnnotation:[],VoidTypeAnnotation:[],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXElement:["openingElement","closingElement","children"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes"],JSXSpreadAttribute:["argument"]}},{}],119:[function(e,n,l){(function(n){"use strict";e("./patch");var t=e("lodash/lang/cloneDeep"),r=e("lodash/collection/contains"),a=e("./traversal"),o=e("lodash/lang/isString"),u=e("lodash/lang/isRegExp"),s=e("lodash/lang/isEmpty"),i=e("./helpers/parse"),c=e("debug/node"),d=e("path"),p=e("util"),f=e("lodash/collection/each"),g=e("lodash/object/has"),h=e("fs"),m=e("./types");l.inherits=p.inherits,l.debug=c("babel"),l.canCompile=function(e,n){var t=n||l.canCompile.EXTENSIONS,a=d.extname(e);return r(t,a)},l.canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"],l.resolve=function(n){try{return e.resolve(n)}catch(l){return null}},l.list=function(e){return e?e.split(","):[]},l.regexify=function(e){if(!e)return new RegExp(/.^/);if(Array.isArray(e)&&(e=e.join("|")),o(e))return new RegExp(e);if(u(e))return e;throw new TypeError("illegal type for regexify")},l.arrayify=function(e){if(!e)return[];if(o(e))return l.list(e);if(Array.isArray(e))return e;throw new TypeError("illegal type for arrayify")},l.booleanify=function(e){return"true"===e?!0:"false"===e?!1:e};var y={enter:function(e,n,l,t){return m.isExpressionStatement(e)&&(e=e.expression),m.isIdentifier(e)&&g(t,e.name)?(this.skip(),t[e.name]):void 0}};l.template=function(e,n,r){var o=l.templates[e];if(!o)throw new ReferenceError("unknown template "+e);if(n===!0&&(r=!0,n=null),o=t(o),s(n)||a(o,y,null,n),o.body.length>1)return o.body;var u=o.body[0];return!r&&m.isExpressionStatement(u)?u.expression:u},l.parseTemplate=function(e,n){var l=i({filename:e},n).program;return a.removeProperties(l)};var x=function(){var e={},t=n+"/transformation/templates";if(!h.existsSync(t))throw new Error("no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues");
return f(h.readdirSync(t),function(n){if("."!==n[0]){var r=d.basename(n,d.extname(n)),a=t+"/"+n,o=h.readFileSync(a,"utf8");e[r]=l.parseTemplate(a,o)}}),e};try{l.templates=e("../../templates.json")}catch(b){if("MODULE_NOT_FOUND"!==b.code)throw b;l.templates=x()}}).call(this,"/lib/babel")},{"../../templates.json":318,"./helpers/parse":25,"./patch":28,"./traversal":112,"./types":117,"debug/node":172,fs:135,"lodash/collection/contains":192,"lodash/collection/each":193,"lodash/lang/cloneDeep":261,"lodash/lang/isEmpty":265,"lodash/lang/isRegExp":270,"lodash/lang/isString":271,"lodash/object/has":276,path:144,util:161}],120:[function(n,l,t){!function(n,r){return"object"==typeof t&&"object"==typeof l?r(t):"function"==typeof e&&e.amd?e(["exports"],r):void r(n.acorn||(n.acorn={}))}(this,function(e){"use strict";function n(e){xt={};for(var n in It)xt[n]=e&&cn(e,n)?e[n]:It[n];if(vt=xt.sourceFile||null,Et(xt.onToken)){var l=xt.onToken;xt.onToken=function(e){l.push(e)}}if(Et(xt.onComment)){var t=xt.onComment;xt.onComment=function(e,n,l,r,a,o){var u={type:e?"Block":"Line",value:n,start:l,end:r};xt.locations&&(u.loc=new J,u.loc.start=a,u.loc.end=o),xt.ranges&&(u.range=[l,r]),t.push(u)}}wa=xt.ecmaVersion>=6?ka:Ea}function l(){this.type=jt,this.value=Tt,this.start=Rt,this.end=St,xt.locations&&(this.loc=new J,this.loc.end=At),xt.ranges&&(this.range=[Rt,St])}function t(){Dt=Nt=wt,xt.locations&&(Bt=u()),Ft=Vt=Ut=!1,qt=[],g(),w()}function r(e,n){var l=kt(bt,e);n+=" ("+l.line+":"+l.column+")";var t=new SyntaxError(n);throw t.pos=e,t.loc=l,t.raisedAt=wt,t}function a(e){return 10===e||13===e||8232===e||8233==e}function o(e,n){this.line=e,this.column=n}function u(){return new o(Ot,wt-Mt)}function s(e){e?(wt=e,Mt=Math.max(0,bt.lastIndexOf("\n",e)),Ot=bt.slice(0,Mt).split(Pa).length):(Ot=1,wt=Mt=0),jt=$t,Lt=[Na],Pt=!0,Xt=Gt=!1,0===wt&&xt.allowHashBang&&"#!"===bt.slice(0,2)&&f(2)}function i(){return Lt[Lt.length-1]}function c(e){var n;return e===qr&&"{"==(n=i()).token?!n.isExpr:e===fr?Pa.test(bt.slice(Nt,Rt)):e===sr||e===Ur||e===$t?!0:e==Dr?i()===Na:!Pt}function d(e,n){St=wt,xt.locations&&(At=u());var l=jt,t=!1;if(jt=e,Tt=n,e===Fr||e===Nr){var r=Lt.pop();r===Fa?t=Pt=!0:r===Na&&i()===Ga?(Lt.pop(),Pt=!1):Pt=!(r&&r.isExpr)}else if(e===Dr){switch(i()){case Ha:Lt.push(Ba);break;case Wa:Lt.push(Fa);break;default:Lt.push(c(l)?Na:Ba)}Pt=!0}else if(e===zr)Lt.push(Fa),Pt=!0;else if(e==Br){var a=l===pr||l===cr||l===vr||l===_r;Lt.push(a?Va:Ua),Pt=!0}else if(e==la);else if(e.keyword&&l==Gr)Pt=!1;else if(e==dr)i()!==Na&&Lt.push(Ga),Pt=!1;else if(e===Yr)i()===qa?Lt.pop():(Lt.push(qa),t=!0),Pt=!1;else if(e===ma)Lt.push(Wa),Lt.push(Ha),Pt=!1;else if(e===ya){var r=Lt.pop();r===Ha&&l===Zr||r===Xa?(Lt.pop(),t=Pt=i()===Wa):t=Pt=!0}else e===Kr?t=Pt=!0:e===Zr&&l===ma?(Lt.length-=2,Lt.push(Xa),Pt=!1):Pt=e.beforeExpr;t||g()}function p(){var e=xt.onComment&&xt.locations&&u(),n=wt,l=bt.indexOf("*/",wt+=2);if(-1===l&&r(wt-2,"Unterminated comment"),wt=l+2,xt.locations){Oa.lastIndex=n;for(var t;(t=Oa.exec(bt))&&t.index<wt;)++Ot,Mt=t.index+t[0].length}xt.onComment&&xt.onComment(!0,bt.slice(n+2,l),n,wt,e,xt.locations&&u())}function f(e){for(var n=wt,l=xt.onComment&&xt.locations&&u(),t=bt.charCodeAt(wt+=e);_t>wt&&10!==t&&13!==t&&8232!==t&&8233!==t;)++wt,t=bt.charCodeAt(wt);xt.onComment&&xt.onComment(!1,bt.slice(n+e,wt),n,wt,l,xt.locations&&u())}function g(){for(;_t>wt;){var e=bt.charCodeAt(wt);if(32===e)++wt;else if(13===e){++wt;var n=bt.charCodeAt(wt);10===n&&++wt,xt.locations&&(++Ot,Mt=wt)}else if(10===e||8232===e||8233===e)++wt,xt.locations&&(++Ot,Mt=wt);else if(e>8&&14>e)++wt;else if(47===e){var n=bt.charCodeAt(wt+1);if(42===n)p();else{if(47!==n)break;f(2)}}else if(160===e)++wt;else{if(!(e>=5760&&Ra.test(String.fromCharCode(e))))break;++wt}}}function h(){var e=bt.charCodeAt(wt+1);if(e>=48&&57>=e)return j(!0);var n=bt.charCodeAt(wt+2);return xt.playground&&63===e?(wt+=2,d(_dotQuestion)):xt.ecmaVersion>=6&&46===e&&46===n?(wt+=3,d(Jr)):(++wt,d(Gr))}function m(){var e=bt.charCodeAt(wt+1);return Pt?(++wt,S()):61===e?R(na,2):R(Zr,1)}function y(){var e=bt.charCodeAt(wt+1);return 61===e?R(na,2):R(fa,1)}function x(){var e=ga,n=1,l=bt.charCodeAt(wt+1);return xt.ecmaVersion>=7&&42===l&&(n++,l=bt.charCodeAt(wt+2),e=ha),61===l&&(n++,e=na),R(e,n)}function b(e){var n=bt.charCodeAt(wt+1);return n===e?xt.playground&&61===bt.charCodeAt(wt+2)?R(na,3):R(124===e?ra:aa,2):61===n?R(na,2):R(124===e?oa:sa,1)}function _(){var e=bt.charCodeAt(wt+1);return 61===e?R(na,2):R(ua,1)}function v(e){var n=bt.charCodeAt(wt+1);return n===e?45==n&&62==bt.charCodeAt(wt+2)&&Pa.test(bt.slice(Nt,wt))?(f(3),g(),w()):R(la,2):61===n?R(na,2):R(pa,1)}function I(e){var n=bt.charCodeAt(wt+1),l=1;if(!Xt&&n===e)return l=62===e&&62===bt.charCodeAt(wt+2)?3:2,61===bt.charCodeAt(wt+l)?R(na,l+1):R(da,l);if(33==n&&60==e&&45==bt.charCodeAt(wt+2)&&45==bt.charCodeAt(wt+3))return f(4),g(),w();if(!Xt){if(Pt&&60===e)return++wt,d(ma);if(62===e){var t=i();if(t===Ha||t===Xa)return++wt,d(ya)}}return 61===n&&(l=61===bt.charCodeAt(wt+2)?3:2),R(ca,l)}function E(e){var n=bt.charCodeAt(wt+1);return 61===n?R(ia,61===bt.charCodeAt(wt+2)?3:2):61===e&&62===n&&xt.ecmaVersion>=6?(wt+=2,d(Xr)):R(61===e?ea:ta,1)}function k(e){switch(e){case 46:return h();case 40:return++wt,d(Br);case 41:return++wt,d(Fr);case 59:return++wt,d(Ur);case 44:return++wt,d(Vr);case 91:return++wt,d(Or);case 93:return++wt,d(Mr);case 123:return++wt,d(Dr);case 125:return++wt,d(Nr);case 63:return++wt,d(Hr);case 35:if(xt.playground)return++wt,d(Qr);case 58:if(++wt,xt.ecmaVersion>=7){var n=bt.charCodeAt(wt);if(58===n)return++wt,d($r)}return d(qr);case 96:return xt.ecmaVersion>=6?(++wt,d(Yr)):!1;case 48:var n=bt.charCodeAt(wt+1);if(120===n||88===n)return A(16);if(xt.ecmaVersion>=6){if(111===n||79===n)return A(8);if(98===n||66===n)return A(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return j(!1);case 34:case 39:return Ht?F():L(e);case 47:return m();case 37:return y();case 42:return x();case 124:case 38:return b(e);case 94:return _();case 43:case 45:return v(e);case 60:case 62:return I(e);case 61:case 33:return E(e);case 126:return R(ta,1)}return!1}function w(){if(Rt=wt,xt.locations&&(Ct=u()),wt>=_t)return d($t);var e=i();if(e===qa)return P();if(e===Wa)return M();var n=bt.charCodeAt(wt);if(e===Ha||e===Xa){if(Ma(n))return G()}else{if(e===Wa)return M();if(Ma(n)||92===n)return q()}var l=k(n);if(l===!1){var t=String.fromCharCode(n);if("\\"===t||Aa.test(t))return q();r(wt,"Unexpected character '"+t+"'")}return l}function R(e,n,l){var t=bt.slice(wt,wt+n);wt+=n,d(e,t,l)}function S(){for(var e,n,l="",t=wt;;){wt>=_t&&r(t,"Unterminated regular expression");var a=un();if(Pa.test(a)&&r(t,"Unterminated regular expression"),e)e=!1;else{if("["===a)n=!0;else if("]"===a&&n)n=!1;else if("/"===a&&!n)break;e="\\"===a}++wt}var l=bt.slice(t,wt);++wt;var o=U(),u=l;if(o){var s=/^[gmsiy]*$/;xt.ecmaVersion>=6&&(s=/^[gmsiyu]*$/),s.test(o)||r(t,"Invalid regular expression flag"),o.indexOf("u")>=0&&!Ja&&(u=u.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x"))}try{new RegExp(u)}catch(i){i instanceof SyntaxError&&r(t,"Error parsing regular expression: "+i.message),r(i)}try{var c=new RegExp(l,o)}catch(p){c=null}return d(Yt,{pattern:l,flags:o,value:c})}function C(e,n){for(var l=wt,t=0,r=0,a=null==n?1/0:n;a>r;++r){var o,u=bt.charCodeAt(wt);if(o=u>=97?u-97+10:u>=65?u-65+10:u>=48&&57>=u?u-48:1/0,o>=e)break;++wt,t=t*e+o}return wt===l||null!=n&&wt-l!==n?null:t}function A(e){wt+=2;var n=C(e);return null==n&&r(Rt+2,"Expected number in radix "+e),Ma(bt.charCodeAt(wt))&&r(wt,"Identifier directly after number"),d(Jt,n)}function j(e){var n=wt,l=!1,t=48===bt.charCodeAt(wt);e||null!==C(10)||r(n,"Invalid number"),46===bt.charCodeAt(wt)&&(++wt,C(10),l=!0);var a=bt.charCodeAt(wt);(69===a||101===a)&&(a=bt.charCodeAt(++wt),(43===a||45===a)&&++wt,null===C(10)&&r(n,"Invalid number"),l=!0),Ma(bt.charCodeAt(wt))&&r(wt,"Identifier directly after number");var o,u=bt.slice(n,wt);return l?o=parseFloat(u):t&&1!==u.length?/[89]/.test(u)||Gt?r(n,"Invalid number"):o=parseInt(u,8):o=parseInt(u,10),d(Jt,o)}function T(){var e,n=bt.charCodeAt(wt);if(123===n?(xt.ecmaVersion<6&&sn(),++wt,e=V(bt.indexOf("}",wt)-wt),++wt,e>1114111&&sn()):e=V(4),65535>=e)return String.fromCharCode(e);var l=(e-65536>>10)+55296,t=(e-65536&1023)+56320;return String.fromCharCode(l,t)}function L(e){for(var n=i()===Ha,l="",t=++wt;;){wt>=_t&&r(Rt,"Unterminated string constant");var o=bt.charCodeAt(wt);if(o===e)break;92!==o||n?38===o&&n?(l+=bt.slice(t,wt),l+=O(),t=wt):(a(o)&&!n&&r(Rt,"Unterminated string constant"),++wt):(l+=bt.slice(t,wt),l+=D(),t=wt)}return l+=bt.slice(t,wt++),d(zt,l)}function P(){for(var e="",n=wt;;){wt>=_t&&r(Rt,"Unterminated template");var l=bt.charCodeAt(wt);if(96===l||36===l&&123===bt.charCodeAt(wt+1))return wt===Rt&&jt===Wr?36===l?(wt+=2,d(zr)):(++wt,d(Yr)):(e+=bt.slice(n,wt),d(Wr,e));92===l?(e+=bt.slice(n,wt),e+=D(),n=wt):a(l)?(e+=bt.slice(n,wt),++wt,13===l&&10===bt.charCodeAt(wt)?(++wt,e+="\n"):e+=String.fromCharCode(l),xt.locations&&(++Ot,Mt=wt),n=wt):++wt}}function O(){var e,n="",l=0,t=bt[wt];"&"!==t&&r(wt,"Entity must start with an ampersand");for(var a=++wt;_t>wt&&l++<10;){if(t=bt[wt++],";"===t){"#"===n[0]?"x"===n[1]?(n=n.substr(2),La.test(n)&&(e=String.fromCharCode(parseInt(n,16)))):(n=n.substr(1),Ta.test(n)&&(e=String.fromCharCode(parseInt(n,10)))):e=Ka[n];break}n+=t}return e?e:(wt=a,"&")}function M(){for(var e="",n=wt;;){wt>=_t&&r(Rt,"Unterminated JSX contents");var l=bt.charCodeAt(wt);switch(l){case 123:case 60:return wt===Rt?k(l):(e+=bt.slice(n,wt),d(Kr,e));case 38:e+=bt.slice(n,wt),e+=O(),n=wt;break;default:a(l)?(e+=bt.slice(n,wt),++wt,13===l&&10===bt.charCodeAt(wt)?(++wt,e+="\n"):e+=String.fromCharCode(l),xt.locations&&(++Ot,Mt=wt),n=wt):++wt}}}function D(){var e=bt.charCodeAt(++wt),n=/^[0-7]+/.exec(bt.slice(wt,wt+3));for(n&&(n=n[0]);n&&parseInt(n,8)>255;)n=n.slice(0,-1);if("0"===n&&(n=null),++wt,n)return Gt&&r(wt-2,"Octal literal in strict mode"),wt+=n.length-1,String.fromCharCode(parseInt(n,8));switch(e){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(V(2));case 117:return T();case 116:return" ";case 98:return"\b";case 118:return"";case 102:return"\f";case 48:return"\x00";case 13:10===bt.charCodeAt(wt)&&++wt;case 10:return xt.locations&&(Mt=wt,++Ot),"";default:return String.fromCharCode(e)}}function N(){var e,n="",l=0,t=un();"&"!==t&&r(wt,"Entity must start with an ampersand");for(var a=++wt;_t>wt&&l++<10;){if(t=un(),wt++,";"===t){"#"===n[0]?"x"===n[1]?(n=n.substr(2),La.test(n)&&(e=String.fromCharCode(parseInt(n,16)))):(n=n.substr(1),Ta.test(n)&&(e=String.fromCharCode(parseInt(n,10)))):e=Ka[n];break}n+=t}return e?e:(wt=a,"&")}function B(e){for(var n="";_t>wt;){var l=un();if(-1!==e.indexOf(l))break;"&"===l?n+=N():(++wt,"\r"===l&&"\n"===un()&&(n+=l,++wt,l="\n"),"\n"===l&&xt.locations&&(Mt=wt,++Ot),n+=l)}return d(er,n)}function F(){var e=bt.charCodeAt(wt);return 34!==e&&39!==e&&r("String literal must starts with a quote"),++wt,B([String.fromCharCode(e)]),e!==bt.charCodeAt(wt)&&sn(),++wt,d(jt,Tt)}function V(e){var n=C(16,e);return null===n&&r(Rt,"Bad character escape sequence"),n}function U(){za=!1;for(var e="",n=!0,l=wt;_t>wt;){var t=bt.charCodeAt(wt);if(Da(t))++wt;else{if(92!==t)break;za=!0,e+=bt.slice(l,wt),117!=bt.charCodeAt(++wt)&&r(wt,"Expecting Unicode escape sequence \\uXXXX"),++wt;var a=V(4),o=String.fromCharCode(a);o||r(wt-1,"Invalid Unicode escape"),(n?Ma(a):Da(a))||r(wt-4,"Invalid Unicode escape"),e+=o,l=wt}n=!1}return e+bt.slice(l,wt)}function q(){var e=U(),n=Ht?Zt:Kt;return!za&&wa(e)&&(n=Pr[e]),d(n,e)}function G(){var e,n=wt;do e=bt.charCodeAt(++wt);while(Da(e)||45===e);return d(Qt,bt.slice(n,wt))}function H(){xt.onToken&&xt.onToken(new l),Dt=Rt,Nt=St,Bt=At,w()}function X(e){if(Gt=e,jt===Jt||jt===zt){if(wt=Rt,xt.locations)for(;Mt>wt;)Mt=bt.lastIndexOf("\n",Mt-2)+1,--Ot;g(),w()}}function W(){this.type=null,this.start=Rt,this.end=null}function J(){this.start=Ct,this.end=null,null!==vt&&(this.source=vt)}function Y(){var n=new e.Node;return xt.locations&&(n.loc=new J),xt.directSourceFile&&(n.sourceFile=xt.directSourceFile),xt.ranges&&(n.range=[Rt,0]),n}function z(){return xt.locations?[Rt,Ct]:Rt}function K(n){var l=new e.Node,t=n;return xt.locations&&(l.loc=new J,l.loc.start=t[1],t=n[0]),l.start=t,xt.directSourceFile&&(l.sourceFile=xt.directSourceFile),xt.ranges&&(l.range=[t,0]),l}function $(e,n){return e.type=n,e.end=Nt,xt.locations&&(e.loc.end=Bt),xt.ranges&&(e.range[1]=Nt),e}function Q(e,n,l){return xt.locations&&(e.loc.end=l[1],l=l[0]),e.type=n,e.end=l,xt.ranges&&(e.range[1]=l),e}function Z(e){return xt.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"use strict"===e.expression.value}function en(e){return jt===e?(H(),!0):!1}function nn(e){return jt===Kt&&Tt===e}function ln(e){return Tt===e&&en(Kt)}function tn(e){ln(e)||sn()}function rn(){return!xt.strictSemicolons&&(jt===$t||jt===Nr||Pa.test(bt.slice(Nt,Rt)))}function an(){en(Ur)||rn()||sn()}function on(e){en(e)||sn()}function un(){return bt.charAt(wt)}function sn(e){r(null!=e?e:Rt,"Unexpected token")}function cn(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function dn(e,n){if(xt.ecmaVersion>=6&&e)switch(e.type){case"Identifier":case"VirtualPropertyExpression":case"MemberExpression":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":e.type="ObjectPattern";for(var l=0;l<e.properties.length;l++){var t=e.properties[l];"init"!==t.kind&&r(t.key.start,"Object pattern can't contain getter or setter"),dn(t.value,n)}break;case"ArrayExpression":e.type="ArrayPattern",pn(e.elements,n);break;case"AssignmentExpression":"="===e.operator?e.type="AssignmentPattern":r(e.left.end,"Only '=' operator can be used for specifying default value.");break;case"MemberExpression":if(!n)break;default:r(e.start,"Assigning to rvalue")}return e}function pn(e,n){if(e.length){for(var l=0;l<e.length-1;l++)dn(e[l],n);var t=e[e.length-1];switch(t.type){case"RestElement":break;case"SpreadElement":t.type="RestElement";var r=t.argument;dn(r,n),"Identifier"!==r.type&&"MemberExpression"!==r.type&&"ArrayPattern"!==r.type&&sn(r.start);break;default:dn(t,n)}}return e}function fn(e){var n=Y();return H(),n.argument=Wn(e),$(n,"SpreadElement")}function gn(){var e=Y();return H(),e.argument=jt===Kt||jt===Or?hn():sn(),$(e,"RestElement")}function hn(){if(xt.ecmaVersion<6)return yl();switch(jt){case Kt:return yl();case Or:var e=Y();return H(),e.elements=mn(Mr,!0),$(e,"ArrayPattern");case Dr:return al(!0);default:sn()}}function mn(e,n){for(var l=[],t=!0;!en(e);){if(t?t=!1:on(Vr),jt===Jr){l.push(yn(gn())),on(e);break}var r;if(n&&jt===Vr)r=null;else{var a=xn();yn(a),r=xn(null,a)}l.push(r)}return l}function yn(e){return en(Hr)&&(e.optional=!0),jt===qr&&(e.typeAnnotation=mt()),$(e,e.type),e}function xn(e,n){if(e=e||z(),n=n||hn(),!en(ea))return n;var l=K(e);return l.operator="=",l.left=n,l.right=Wn(),$(l,"AssignmentPattern")}function bn(e,n){switch(e.type){case"Identifier":(va(e.name)||Ia(e.name))&&r(e.start,"Defining '"+e.name+"' in strict mode"),cn(n,e.name)&&r(e.start,"Argument name clash in strict mode"),n[e.name]=!0;break;case"ObjectPattern":for(var l=0;l<e.properties.length;l++){var t=e.properties[l];"SpreadProperty"===t.type?bn(t.argument,n):bn(t.value,n)}break;case"ArrayPattern":for(var l=0;l<e.elements.length;l++){var a=e.elements[l];a&&bn(a,n)}break;case"RestElement":return bn(e.argument,n)}}function _n(e,n){if(!(xt.ecmaVersion>=6)){var l,t=e.key;switch(t.type){case"Identifier":l=t.name;break;case"Literal":l=String(t.value);break;default:return}var a,o=e.kind||"init";if(cn(n,l)){a=n[l];var u="init"!==o;((Gt||u)&&a[o]||!(u^a.init))&&r(t.start,"Redefinition of property")}else a=n[l]={init:!1,get:!1,set:!1};a[o]=!0}}function vn(e,n){switch(e.type){case"Identifier":Gt&&(Ia(e.name)||va(e.name))&&r(e.start,(n?"Binding ":"Assigning to ")+e.name+" in strict mode");break;case"MemberExpression":n&&r(e.start,"Binding to member expression");break;case"ObjectPattern":for(var l=0;l<e.properties.length;l++){var t=e.properties[l];"Property"===t.type&&(t=t.value),vn(t,n)}break;case"ArrayPattern":for(var l=0;l<e.elements.length;l++){var a=e.elements[l];a&&vn(a,n)}break;case"AssignmentPattern":vn(e.left);break;case"SpreadProperty":case"VirtualPropertyExpression":break;case"RestElement":vn(e.argument);break;default:r(e.start,"Assigning to rvalue")}}function In(e){var n=!0;for(e.body||(e.body=[]);jt!==$t;){var l=En(!0,!0);e.body.push(l),n&&Z(l)&&X(!0),n=!1}return H(),$(e,"Program")}function En(e,n){var l=jt,t=Y();switch(l){case nr:case rr:return kn(t,l.keyword);case ar:return wn(t);case ur:return Rn(t);case cr:return Sn(t);case dr:return!e&&xt.ecmaVersion>=6&&sn(),Cn(t);case kr:return e||sn(),gl(t,!0);case pr:return An(t);case fr:return jn(t);case gr:return Tn(t);case hr:return Ln(t);case mr:return Pn(t);case xr:case br:e||sn();case yr:return On(t,l.keyword);case _r:return Mn(t);case vr:return Dn(t);case Dr:return Un();case Ur:return Nn(t);case Rr:case Sr:return n||xt.allowImportExportEverywhere||r(Rt,"'import' and 'export' may only appear at the top level"),l===Sr?_l(t):xl(t);case Kt:if(xt.ecmaVersion>=7&&"private"===Tt)return H(),fl(t);default:var a=Tt,o=Xn();if(xt.ecmaVersion>=7&&l===Kt&&"async"===a&&jt===dr&&!rn()){H();var u=Cn(t);return u.async=!0,u}if(l===Kt&&"Identifier"===o.type){if(en(qr))return Bn(t,a,o);if("declare"===o.name){if(jt===kr||jt===Kt||jt===dr||jt===yr)return ql(t)}else if(jt===Kt){if("interface"===o.name)return Jl(t);if("type"===o.name)return Yl(t)}}if("FunctionExpression"===o.type&&o.async){if(o.id)return o.type="FunctionDeclaration",o;sn(o.start+"async function ".length)}return Fn(t,o)}}function kn(e,n){var l="break"==n;H(),en(Ur)||rn()?e.label=null:jt!==Kt?sn():(e.label=yl(),an());for(var t=0;t<qt.length;++t){var a=qt[t];if(null==e.label||a.name===e.label.name){if(null!=a.kind&&(l||"loop"===a.kind))break;if(e.label&&l)break}}return t===qt.length&&r(e.start,"Unsyntactic "+n),$(e,l?"BreakStatement":"ContinueStatement")}function wn(e){return H(),an(),$(e,"DebuggerStatement")}function Rn(e){return H(),qt.push($a),e.body=En(!1),qt.pop(),on(_r),e.test=Vn(),xt.ecmaVersion>=6?en(Ur):an(),$(e,"DoWhileStatement")}function Sn(e){if(H(),qt.push($a),on(Br),jt===Ur)return qn(e,null);if(jt===yr||jt===xr){var n=Y(),l=jt.keyword,t=jt===xr;return H(),Hn(n,!0,l),$(n,"VariableDeclaration"),!(jt===Lr||xt.ecmaVersion>=6&&nn("of"))||1!==n.declarations.length||t&&n.declarations[0].init?qn(e,n):Gn(e,n)}var r={start:0},n=Xn(!0,r);return jt===Lr||xt.ecmaVersion>=6&&nn("of")?(dn(n),vn(n),Gn(e,n)):(r.start&&sn(r.start),qn(e,n))}function Cn(e){return H(),sl(e,!0,!1)}function An(e){return H(),e.test=Vn(),e.consequent=En(!1),e.alternate=en(sr)?En(!1):null,$(e,"IfStatement")}function jn(e){return Ft||xt.allowReturnOutsideFunction||r(Rt,"'return' outside of function"),H(),en(Ur)||rn()?e.argument=null:(e.argument=Xn(),an()),$(e,"ReturnStatement")}function Tn(e){H(),e.discriminant=Vn(),e.cases=[],on(Dr),qt.push(Qa);for(var n,l;jt!=Nr;)if(jt===lr||jt===or){var t=jt===lr;n&&$(n,"SwitchCase"),e.cases.push(n=Y()),n.consequent=[],H(),t?n.test=Xn():(l&&r(Dt,"Multiple default clauses"),l=!0,n.test=null),on(qr)}else n||sn(),n.consequent.push(En(!0));return n&&$(n,"SwitchCase"),H(),qt.pop(),$(e,"SwitchStatement")}function Ln(e){return H(),Pa.test(bt.slice(Nt,Rt))&&r(Nt,"Illegal newline after throw"),e.argument=Xn(),an(),$(e,"ThrowStatement")}function Pn(e){if(H(),e.block=Un(),e.handler=null,jt===tr){var n=Y();H(),on(Br),n.param=hn(),vn(n.param,!0),on(Fr),n.guard=null,n.body=Un(),e.handler=$(n,"CatchClause")}return e.guardedHandlers=Wt,e.finalizer=en(ir)?Un():null,e.handler||e.finalizer||r(e.start,"Missing catch or finally clause"),$(e,"TryStatement")}function On(e,n){return H(),Hn(e,!1,n),an(),$(e,"VariableDeclaration")}function Mn(e){return H(),e.test=Vn(),qt.push($a),e.body=En(!1),qt.pop(),$(e,"WhileStatement")}function Dn(e){return Gt&&r(Rt,"'with' in strict mode"),H(),e.object=Vn(),e.body=En(!1),$(e,"WithStatement")}function Nn(e){return H(),$(e,"EmptyStatement")}function Bn(e,n,l){for(var t=0;t<qt.length;++t)qt[t].name===n&&r(l.start,"Label '"+n+"' is already declared");var a=jt.isLoop?"loop":jt===gr?"switch":null;return qt.push({name:n,kind:a}),e.body=En(!0),qt.pop(),e.label=l,$(e,"LabeledStatement")}function Fn(e,n){return e.expression=n,an(),$(e,"ExpressionStatement")}function Vn(){on(Br);var e=Xn();return on(Fr),e}function Un(e){var n,l=Y(),t=!0;for(l.body=[],on(Dr);!en(Nr);){var r=En(!0);l.body.push(r),t&&e&&Z(r)&&(n=Gt,X(Gt=!0)),t=!1}return n===!1&&X(!1),$(l,"BlockStatement")}function qn(e,n){return e.init=n,on(Ur),e.test=jt===Ur?null:Xn(),on(Ur),e.update=jt===Fr?null:Xn(),on(Fr),e.body=En(!1),qt.pop(),$(e,"ForStatement")}function Gn(e,n){var l=jt===Lr?"ForInStatement":"ForOfStatement";return H(),e.left=n,e.right=Xn(),on(Fr),e.body=En(!1),qt.pop(),$(e,l)}function Hn(e,n,l){for(e.declarations=[],e.kind=l;;){var t=Y();if(t.id=hn(),vn(t.id,!0),jt===qr&&(t.id.typeAnnotation=mt(),$(t.id,t.id.type)),t.init=en(ea)?Wn(n):l===br.keyword?sn():null,e.declarations.push($(t,"VariableDeclarator")),!en(Vr))break}return e}function Xn(e,n){var l=z(),t=Wn(e,n);if(jt===Vr){var r=K(l);for(r.expressions=[t];en(Vr);)r.expressions.push(Wn(e,n));return $(r,"SequenceExpression")}return t}function Wn(e,n,l){var t;n?t=!1:(n={start:0},t=!0);var r=z(),a=Jn(e,n);if(l&&(a=l(a,r)),jt.isAssign){var o=K(r);return o.operator=Tt,o.left=jt===ea?dn(a):a,n.start=0,vn(a),H(),o.right=Wn(e),$(o,"AssignmentExpression")}return t&&n.start&&sn(n.start),a}function Jn(e,n){var l=z(),t=Yn(e,n);if(n&&n.start)return t;if(en(Hr)){var a=K(l);if(xt.playground&&en(ea)){var o=a.left=dn(t);return"MemberExpression"!==o.type&&r(o.start,"You can only use member expressions in memoization assignment"),a.right=Wn(e),a.operator="?=",$(a,"AssignmentExpression")}return a.test=t,a.consequent=Wn(),on(qr),a.alternate=Wn(e),$(a,"ConditionalExpression")}return t}function Yn(e,n){var l=z(),t=Kn(n);return n&&n.start?t:zn(t,l,-1,e)}function zn(e,n,l,t){var r=jt.binop;if(null!=r&&(!t||jt!==Lr)&&r>l){var a=K(n);a.left=e,a.operator=Tt;var o=jt;H();var u=z();return a.right=zn(Kn(),u,o.rightAssociative?r-1:r,t),$(a,o===ra||o===aa?"LogicalExpression":"BinaryExpression"),zn(a,n,l,t)}return e}function Kn(e){if(jt.prefix){var n=Y(),l=jt.isUpdate;return n.operator=Tt,n.prefix=!0,H(),n.argument=Kn(),e&&e.start&&sn(e.start),l?vn(n.argument):Gt&&"delete"===n.operator&&"Identifier"===n.argument.type&&r(n.start,"Deleting local variable in strict mode"),$(n,l?"UpdateExpression":"UnaryExpression")}var t=z(),a=$n(e);if(e&&e.start)return a;for(;jt.postfix&&!rn();){var n=K(t);n.operator=Tt,n.prefix=!1,n.argument=a,vn(a),H(),a=$(n,"UpdateExpression")}return a}function $n(e){var n=z(),l=Zn(e);return e&&e.start?l:Qn(l,n)}function Qn(e,n,l){if(xt.playground&&en(Qr)){var t=K(n);return t.object=e,t.property=yl(!0),t.arguments=en(Br)?ml(Fr,!1):[],Qn($(t,"BindMemberExpression"),n,l)}if(en($r)){var t=K(n);return t.object=e,t.property=yl(!0),Qn($(t,"VirtualPropertyExpression"),n,l)}if(en(Gr)){var t=K(n);return t.object=e,t.property=yl(!0),t.computed=!1,Qn($(t,"MemberExpression"),n,l)}if(en(Or)){var t=K(n);return t.object=e,t.property=Xn(),t.computed=!0,on(Mr),Qn($(t,"MemberExpression"),n,l)}if(!l&&en(Br)){var t=K(n);return t.callee=e,t.arguments=ml(Fr,!1),Qn($(t,"CallExpression"),n,l)}if(jt===Yr){var t=K(n);return t.tag=e,t.quasi=rl(),Qn($(t,"TaggedTemplateExpression"),n,l)}return e}function Zn(e){switch(jt){case Er:var n=Y();return H(),$(n,"ThisExpression");case Cr:if(Vt)return El();case Kt:var l=z(),n=Y(),t=yl(jt!==Kt);if(xt.ecmaVersion>=7)if("async"===t.name){if(jt===Br){H();var r;if(jt!==Fr){var a=Xn();r="SequenceExpression"===a.type?a.expressions:[a]}else r=[];return on(Fr),en(Xr)?dl(n,r,!0):(n.callee=t,n.arguments=r,Qn($(n,"CallExpression"),l))}if(jt===Kt)return t=yl(),en(Xr)?dl(n,[t],!0):t;if(jt===dr&&!rn())return H(),sl(n,!1,!0)}else if("await"===t.name&&Ut)return kl(n);return!rn()&&en(Xr)?dl(K(l),[t]):t;case Yt:var n=Y();return n.regex={pattern:Tt.pattern,flags:Tt.flags},n.value=Tt.value,n.raw=bt.slice(Rt,St),H(),$(n,"Literal");case Jt:case zt:case Kr:var n=Y();return n.value=Tt,n.raw=bt.slice(Rt,St),H(),$(n,"Literal");case Ar:case jr:case Tr:var n=Y();return n.value=jt.atomValue,n.raw=jt.keyword,H(),$(n,"Literal");case Br:return nl();case Or:var n=Y();return H(),xt.ecmaVersion>=7&&jt===cr?wl(n,!1):(n.elements=ml(Mr,!0,!0,e),$(n,"ArrayExpression"));case Dr:return al(!1,e);case dr:var n=Y();return H(),sl(n,!1,!1);case kr:return gl(Y(),!1);case Ir:return ll();case Yr:return rl();case Qr:return el();case ma:return Fl();default:sn()}}function el(){var e=Y();H();var n=z();return e.callee=Qn(Zn(),n,!0),e.arguments=en(Br)?ml(Fr,!1):[],$(e,"BindFunctionExpression")}function nl(){var e,n=z();if(xt.ecmaVersion>=6){if(H(),xt.ecmaVersion>=7&&jt===cr)return wl(K(n),!0);for(var l,t,r=z(),a=[],o=!0,u={start:0},s=function(e,n){if(jt===qr){var l=K(n);return l.expression=e,l.typeAnnotation=mt(),$(l,"TypeCastExpression")}return e};jt!==Fr;){if(o?o=!1:on(Vr),jt===Jr){var i=z();l=Rt,a.push(s(gn(),i));break}jt!==Br||t||(t=Rt),a.push(Wn(!1,u,s))}var c=z();if(on(Fr),!rn()&&en(Xr)){t&&sn(t);for(var d=0;d<a.length;d++){var p=a[d];if("TypeCastExpression"===p.type){var f=p.expression;f.returnType=p.typeAnnotation,a[d]=f}}return dl(K(n),a)}a.length||sn(Dt),l&&sn(l),u.start&&sn(u.start),a.length>1?(e=K(r),e.expressions=a,Q(e,"SequenceExpression",c)):e=a[0]}else e=Vn();if(xt.preserveParens){var g=K(n);return g.expression=e,$(g,"ParenthesizedExpression")}return e}function ll(){var e=Y();H();var n=z();return e.callee=Qn(Zn(),n,!0),e.arguments=en(Br)?ml(Fr,!1):Wt,$(e,"NewExpression")}function tl(){var e=Y();return e.value={raw:bt.slice(Rt,St),cooked:Tt},H(),e.tail=jt===Yr,$(e,"TemplateElement")}function rl(){var e=Y();H(),e.expressions=[];var n=tl();for(e.quasis=[n];!n.tail;)on(zr),e.expressions.push(Xn()),on(Nr),e.quasis.push(n=tl());return H(),$(e,"TemplateLiteral")}function al(e,n){var l=Y(),t=!0,r={};for(l.properties=[],H();!en(Nr);){if(t)t=!1;else if(on(Vr),xt.allowTrailingCommas&&en(Nr))break;var a,o=Y(),u=!1,s=!1;if(xt.ecmaVersion>=7&&jt===Jr)o=fn(),o.type="SpreadProperty",l.properties.push(o);else{if(xt.ecmaVersion>=6&&(o.method=!1,o.shorthand=!1,(e||n)&&(a=z()),e||(u=en(ga))),xt.ecmaVersion>=7&&nn("async")){var i=yl();jt===qr||jt===Br?o.key=i:(s=!0,ol(o))}else ol(o);var c;Nl("<")&&(c=zl(),jt!==Br&&sn()),en(qr)?(o.value=e?xn():Wn(!1,n),o.kind="init"):xt.ecmaVersion>=6&&jt===Br?(e&&sn(),o.kind="init",o.method=!0,o.value=il(u,s)):xt.ecmaVersion>=5&&!o.computed&&"Identifier"===o.key.type&&("get"===o.key.name||"set"===o.key.name||xt.playground&&"memo"===o.key.name)&&jt!=Vr&&jt!=Nr?((u||s||e)&&sn(),o.kind=o.key.name,ol(o),o.value=il(!1,!1)):xt.ecmaVersion>=6&&!o.computed&&"Identifier"===o.key.type?(o.kind="init",e?o.value=xn(a,o.key):jt===ea&&n?(n.start||(n.start=Rt),o.value=xn(a,o.key)):o.value=o.key,o.shorthand=!0):sn(),o.value.typeParameters=c,_n(o,r),l.properties.push($(o,"Property"))}}return $(l,e?"ObjectPattern":"ObjectExpression")}function ol(e){if(xt.ecmaVersion>=6){if(en(Or))return e.computed=!0,e.key=Xn(),void on(Mr);e.computed=!1}e.key=jt===Jt||jt===zt?Zn():yl(!0)}function ul(e,n){e.id=null,xt.ecmaVersion>=6&&(e.generator=!1,e.expression=!1),xt.ecmaVersion>=7&&(e.async=n)}function sl(e,n,l,t){return ul(e,l),xt.ecmaVersion>=6&&(e.generator=en(ga)),(n||jt===Kt)&&(e.id=yl()),Nl("<")&&(e.typeParameters=zl()),cl(e),pl(e,t),$(e,n?"FunctionDeclaration":"FunctionExpression")}function il(e,n){var l=Y();ul(l,n),cl(l);var t;return xt.ecmaVersion>=6?(l.generator=e,t=!0):t=!1,pl(l,t),$(l,"FunctionExpression")}function cl(e){on(Br),e.params=mn(Fr,!1),jt===qr&&(e.returnType=mt())}function dl(e,n,l){return ul(e,l),e.params=pn(n,!0),pl(e,!0),$(e,"ArrowFunctionExpression")}function pl(e,n){var l=n&&jt!==Dr,t=Ut;if(Ut=e.async,l)e.body=Wn(),e.expression=!0;else{var r=Ft,a=Vt,o=qt;Ft=!0,Vt=e.generator,qt=[],e.body=Un(!0),e.expression=!1,Ft=r,Vt=a,qt=o}if(Ut=t,Gt||!l&&e.body.body.length&&Z(e.body.body[0])){var u={};e.id&&bn(e.id,{});for(var s=0;s<e.params.length;s++)bn(e.params[s],u)}}function fl(e){e.declarations=[];do e.declarations.push(yl());while(en(Vr));return an(),$(e,"PrivateDeclaration")}function gl(e,n){H(),e.id=jt===Kt?yl():n?sn():null,Nl("<")&&(e.typeParameters=zl()),e.superClass=en(wr)?$n():null,e.superClass&&Nl("<")&&(e.superTypeParameters=Kl()),nn("implements")&&(H(),e.implements=hl());var l=Y();for(l.body=[],on(Dr);!en(Nr);)if(!en(Ur)){var t=Y();if(xt.ecmaVersion>=7&&nn("private"))H(),l.body.push(fl(t));else{var r=en(ga),a=!1;ol(t),jt===Br||t.computed||"Identifier"!==t.key.type||"static"!==t.key.name?t["static"]=!1:((r||a)&&sn(),t["static"]=!0,r=en(ga),ol(t)),jt===Br||t.computed||"Identifier"!==t.key.type||"async"!==t.key.name||(a=!0,ol(t)),jt!==Br&&!t.computed&&"Identifier"===t.key.type&&("get"===t.key.name||"set"===t.key.name)||xt.playground&&"memo"===t.key.name?((r||a)&&sn(),t.kind=t.key.name,ol(t)):t.kind="";var o=!1;if(jt===qr&&(t.typeAnnotation=mt(),o=!0),xt.playground&&en(ea)&&(t.value=Wn(),o=!0),o)an(),l.body.push($(t,"ClassProperty"));else{var u;Nl("<")&&(u=zl()),t.value=il(r,a),t.value.typeParameters=u,l.body.push($(t,"MethodDefinition")),en(Ur)}}}return e.body=$(l,"ClassBody"),$(e,n?"ClassDeclaration":"ClassExpression")}function hl(){var e=[];do{var n=Y();n.id=yl(),n.typeParameters=Nl("<")?Kl():null,e.push($(n,"ClassImplements"))}while(en(Vr));return e}function ml(e,n,l,t){for(var r=[],a=!0;!en(e);){if(a)a=!1;else if(on(Vr),n&&xt.allowTrailingCommas&&en(e))break;r.push(l&&jt===Vr?null:jt===Jr?fn(t):Wn(!1,t))}return r}function yl(e){var n=Y();return e&&"everywhere"==xt.forbidReserved&&(e=!1),jt===Kt?(!e&&(xt.forbidReserved&&(3===xt.ecmaVersion?ba:_a)(Tt)||Gt&&va(Tt))&&-1==bt.slice(Rt,St).indexOf("\\")&&r(Rt,"The keyword '"+Tt+"' is reserved"),n.name=Tt):e&&jt.keyword?n.name=jt.keyword:sn(),H(),$(n,"Identifier")}function xl(e){if(H(),jt===yr||jt===br||jt===xr||jt===dr||jt===kr||nn("async")||nn("type"))e.declaration=En(!0),e["default"]=!1,e.specifiers=null,e.source=null;else if(en(or)){var n=Wn();if(n.id)switch(n.type){case"FunctionExpression":n.type="FunctionDeclaration";break;case"ClassExpression":n.type="ClassDeclaration"}e.declaration=n,e["default"]=!0,e.specifiers=null,e.source=null,an()}else{var l=jt===ga;e.declaration=null,e["default"]=!1,e.specifiers=bl(),ln("from")?e.source=jt===zt?Zn():sn():(l&&sn(),e.source=null),an()}return $(e,"ExportDeclaration")}function bl(){var e=[],n=!0;if(jt===ga){var l=Y();H(),e.push($(l,"ExportBatchSpecifier"))}else for(on(Dr);!en(Nr);){if(n)n=!1;else if(on(Vr),xt.allowTrailingCommas&&en(Nr))break;var l=Y();l.id=yl(jt===or),l.name=ln("as")?yl(!0):null,e.push($(l,"ExportSpecifier"))}return e}function _l(e){H(),e.isType=!1,e.specifiers=[];var n;if(nn("type")){var l=z();n=yl(),jt===Kt&&"from"!==Tt||jt===Dr||jt===ga?e.isType=!0:(e.specifiers.push(Il(n,l)),en(Vr))}return jt===zt?(n&&sn(n.start),e.source=Zn()):(nn("from")||vl(e.specifiers),tn("from"),e.source=jt===zt?Zn():sn()),an(),$(e,"ImportDeclaration")}function vl(e){var n=!0;if(jt===Kt){var l=z(),t=yl();if(e.push(Il(t,l)),!en(Vr))return e}if(jt===ga){var r=Y();return H(),tn("as"),r.name=yl(),vn(r.name,!0),e.push($(r,"ImportBatchSpecifier")),e}for(on(Dr);!en(Nr);){if(n)n=!1;else if(on(Vr),xt.allowTrailingCommas&&en(Nr))break;var r=Y();r.id=yl(!0),r.name=ln("as")?yl():null,vn(r.name||r.id,!0),r["default"]=!1,e.push($(r,"ImportSpecifier"))}return e}function Il(e,n){var l=K(n);return l.id=e,vn(l.id,!0),l.name=null,l["default"]=!0,$(l,"ImportSpecifier")}function El(){var e=Y();return H(),en(Ur)||rn()?(e.delegate=!1,e.argument=null):(e.delegate=en(ga),e.argument=Wn()),$(e,"YieldExpression")}function kl(e){return(en(Ur)||rn())&&sn(),e.all=en(ga),e.argument=Wn(!0),$(e,"AwaitExpression")}function wl(e,n){for(e.blocks=[];jt===cr;){var l=Y();H(),on(Br),l.left=hn(),vn(l.left,!0),tn("of"),l.right=Xn(),on(Fr),e.blocks.push($(l,"ComprehensionBlock"))}return e.filter=en(pr)?Vn():null,e.body=Xn(),on(n?Fr:Mr),e.generator=n,$(e,"ComprehensionExpression")
}function Rl(e){return"JSXIdentifier"===e.type?e.name:"JSXNamespacedName"===e.type?e.namespace.name+":"+e.name.name:"JSXMemberExpression"===e.type?Rl(e.object)+"."+Rl(e.property):void 0}function Sl(){var e=Y();return jt===Qt?e.name=Tt:jt.keyword?e.name=jt.keyword:sn(),H(),$(e,"JSXIdentifier")}function Cl(){var e=z(),n=Sl();if(!en(qr))return n;var l=K(e);return l.namespace=n,l.name=Sl(),$(l,"JSXNamespacedName")}function Al(){for(var e=z(),n=Cl();en(Gr);){var l=K(e);l.object=n,l.property=Sl(),n=$(l,"JSXMemberExpression")}return n}function jl(){switch(jt){case Dr:var e=Ll();return"JSXEmptyExpression"===e.expression.type&&r(e.start,"JSX attributes must only be assigned a non-empty expression"),e;case ma:return Fl();case Kr:case zt:return Zn();default:r(Rt,"JSX value should be either an expression or a quoted JSX text")}}function Tl(){jt!==Nr&&sn();var e;return e=Rt,Rt=Nt,Nt=e,e=Ct,Ct=Bt,Bt=e,$(Y(),"JSXEmptyExpression")}function Ll(){var e=Y();return H(),e.expression=jt===Nr?Tl():Xn(),on(Nr),$(e,"JSXExpressionContainer")}function Pl(){var e=Y();return en(Dr)?(on(Jr),e.argument=Wn(),on(Nr),$(e,"JSXSpreadAttribute")):(e.name=Cl(),e.value=en(ea)?jl():null,$(e,"JSXAttribute"))}function Ol(e){var n=K(e);for(n.attributes=[],n.name=Al();jt!==Zr&&jt!==ya;)n.attributes.push(Pl());return n.selfClosing=en(Zr),on(ya),$(n,"JSXOpeningElement")}function Ml(e){var n=K(e);return n.name=Al(),on(ya),$(n,"JSXClosingElement")}function Dl(e){var n=K(e),l=[],t=Ol(e),a=null;if(!t.selfClosing){e:for(;;)switch(jt){case ma:if(e=z(),H(),en(Zr)){a=Ml(e);break e}l.push(Dl(e));break;case Kr:l.push(Zn());break;case Dr:l.push(Ll());break;default:sn()}Rl(a.name)!==Rl(t.name)&&r(a.start,"Expected corresponding JSX closing tag for <"+Rl(t.name)+">")}return n.openingElement=t,n.closingElement=a,n.children=l,$(n,"JSXElement")}function Nl(e){return jt===ca&&Tt===e}function Bl(e){Nl(e)?H():sn()}function Fl(){var e=z();return H(),Dl(e)}function Vl(e){return H(),Xl(e,!0),$(e,"DeclareClass")}function Ul(e){H();var n=e.id=yl(),l=Y(),t=Y();l.typeParameters=Nl("<")?zl():null,on(Br);var r=st();return l.params=r.params,l.rest=r.rest,on(Fr),on(qr),l.returnType=ht(),t.typeAnnotation=$(l,"FunctionTypeAnnotation"),n.typeAnnotation=$(t,"TypeAnnotation"),$(n,n.type),an(),$(e,"DeclareFunction")}function ql(e){return jt===kr?Vl(e):jt===dr?Ul(e):jt===yr?Gl(e):nn("module")?Hl(e):void sn()}function Gl(e){return H(),e.id=yt(),an(),$(e,"DeclareVariable")}function Hl(e){H(),e.id=jt===zt?Zn():yl();var n=e.body=Y(),l=n.body=[];for(on(Dr);jt!==Nr;){var t=Y();H(),l.push(ql(t))}return on(Nr),$(n,"BlockStatement"),$(e,"DeclareModule")}function Xl(e,n){if(e.id=yl(),e.typeParameters=Nl("<")?zl():null,e.extends=[],en(wr))do e.extends.push(Wl());while(en(Vr));e.body=lt(n)}function Wl(){var e=Y();return e.id=yl(),e.typeParameters=Nl("<")?Kl():null,$(e,"InterfaceExtends")}function Jl(e){return Xl(e,!1),$(e,"InterfaceDeclaration")}function Yl(e){return e.id=yl(),e.typeParameters=Nl("<")?zl():null,on(ea),e.right=ht(),an(),$(e,"TypeAlias")}function zl(){var e=Y();for(e.params=[],Bl("<");!Nl(">");)e.params.push(yl()),Nl(">")||on(Vr);return Bl(">"),$(e,"TypeParameterDeclaration")}function Kl(){var e=Y(),n=Xt;for(e.params=[],Xt=!0,Bl("<");!Nl(">");)e.params.push(ht()),Nl(">")||on(Vr);return Bl(">"),Xt=n,$(e,"TypeParameterInstantiation")}function $l(){return jt===Jt||jt===zt?Zn():yl(!0)}function Ql(e,n){return e.static=n,on(Or),e.id=$l(),on(qr),e.key=ht(),on(Mr),on(qr),e.value=ht(),$(e,"ObjectTypeIndexer")}function Zl(e){for(e.params=[],e.rest=null,e.typeParameters=null,Nl("<")&&(e.typeParameters=zl()),on(Br);jt===Kt;)e.params.push(ut()),jt!==Fr&&on(Vr);return en(Jr)&&(e.rest=ut()),on(Fr),on(qr),e.returnType=ht(),$(e,"FunctionTypeAnnotation")}function et(e,n,l){var t=K(e);return t.value=Zl(K(e)),t.static=n,t.key=l,t.optional=!1,$(t,"ObjectTypeProperty")}function nt(e,n){var l=Y();return e.static=n,e.value=Zl(l),$(e,"ObjectTypeCallProperty")}function lt(e){var n,l,t,r=Y(),a=!1;for(r.callProperties=[],r.properties=[],r.indexers=[],on(Dr);jt!==Nr;){var o=z();n=Y(),e&&nn("static")&&(H(),t=!0),jt===Or?r.indexers.push(Ql(n,t)):jt===Br||Nl("<")?r.callProperties.push(nt(n,e)):(l=t&&jt===qr?yl():$l(),Nl("<")||jt===Br?r.properties.push(et(o,t,l)):(en(Hr)&&(a=!0),on(qr),n.key=l,n.value=ht(),n.optional=a,n.static=t,r.properties.push($(n,"ObjectTypeProperty")))),en(Ur)||jt===Nr||sn()}return on(Nr),$(r,"ObjectTypeAnnotation")}function tt(e,n){var l=K(e);for(l.typeParameters=null,l.id=n;en(Gr);){var t=K(e);t.qualification=l.id,t.id=yl(),l.id=$(t,"QualifiedTypeIdentifier")}return Nl("<")&&(l.typeParameters=Kl()),$(l,"GenericTypeAnnotation")}function rt(){var e=Y();return on(Pr["void"]),$(e,"VoidTypeAnnotation")}function at(){var e=Y();return on(Pr["typeof"]),e.argument=ct(),$(e,"TypeofTypeAnnotation")}function ot(){var e=Y();for(e.types=[],on(Or);_t>wt&&jt!==Mr&&(e.types.push(ht()),jt!==Mr);)on(Vr);return on(Mr),$(e,"TupleTypeAnnotation")}function ut(){var e=!1,n=Y();return n.name=yl(),en(Hr)&&(e=!0),on(qr),n.optional=e,n.typeAnnotation=ht(),$(n,"FunctionTypeParam")}function st(){for(var e={params:[],rest:null};jt===Kt;)e.params.push(ut()),jt!==Fr&&on(Vr);return en(Jr)&&(e.rest=ut()),e}function it(e,n,l){switch(l.name){case"any":return $(n,"AnyTypeAnnotation");case"bool":case"boolean":return $(n,"BooleanTypeAnnotation");case"number":return $(n,"NumberTypeAnnotation");case"string":return $(n,"StringTypeAnnotation");default:return tt(e,l)}}function ct(){var e,n,l=z(),t=Y(),a=!1;switch(jt){case Kt:return it(l,t,yl());case Dr:return lt();case Or:return ot();case ca:if("<"===Tt)return t.typeParameters=zl(),on(Br),e=st(),t.params=e.params,t.rest=e.rest,on(Fr),on(Xr),t.returnType=ht(),$(t,"FunctionTypeAnnotation");case Br:H();var o;return jt!==Fr&&jt!==Jr&&(jt===Kt||(a=!0)),a?(o&&Fr?n=o:(n=ht(),on(Fr)),en(Xr)&&r(t,"Unexpected token =>. It looks like you are trying to write a function type, but you ended up writing a grouped type followed by an =>, which is a syntax error. Remember, function type parameters are named so function types look like (name1: type1, name2: type2) => returnType. You probably wrote (type1) => returnType"),n):(e=st(),t.params=e.params,t.rest=e.rest,on(Fr),on(Xr),t.returnType=ht(),t.typeParameters=null,$(t,"FunctionTypeAnnotation"));case zt:return t.value=Tt,t.raw=bt.slice(Rt,St),H(),$(t,"StringLiteralTypeAnnotation");default:if(jt.keyword)switch(jt.keyword){case"void":return rt();case"typeof":return at()}}sn()}function dt(){var e=Y(),n=e.elementType=ct();return jt===Or?(on(Or),on(Mr),$(e,"ArrayTypeAnnotation")):n}function pt(){var e=Y();return en(Hr)?(e.typeAnnotation=pt(),$(e,"NullableTypeAnnotation")):dt()}function ft(){var e=Y(),n=pt();for(e.types=[n];en(sa);)e.types.push(pt());return 1===e.types.length?n:$(e,"IntersectionTypeAnnotation")}function gt(){var e=Y(),n=ft();for(e.types=[n];en(oa);)e.types.push(ft());return 1===e.types.length?n:$(e,"UnionTypeAnnotation")}function ht(){var e=Xt;Xt=!0;var n=gt();return Xt=e,n}function mt(){var e=Y(),n=Xt;return Xt=!0,on(qr),e.typeAnnotation=ht(),Xt=n,$(e,"TypeAnnotation")}function yt(e,n){var l=(Y(),yl()),t=!1;return n&&en(Hr)&&(on(Hr),t=!0),(e||jt===qr)&&(l.typeAnnotation=mt(),$(l,l.type)),t&&(l.optional=!0,$(l,l.type)),l}e.version="0.11.1";var xt,bt,_t,vt;e.parse=function(e,l){bt=String(e),_t=bt.length,n(l),s();var r=xt.locations?[wt,u()]:wt;return t(),xt.strictMode&&(Gt=!0),In(xt.program||K(r))};var It=e.defaultOptions={strictMode:!1,playground:!1,ecmaVersion:5,strictSemicolons:!1,allowTrailingCommas:!0,forbidReserved:!1,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowHashBang:!1,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1};e.parseExpressionAt=function(e,l,r){return bt=String(e),_t=bt.length,n(r),s(l),t(),Xn()};var Et=function(e){return"[object Array]"===Object.prototype.toString.call(e)},kt=e.getLineInfo=function(e,n){for(var l=1,t=0;;){Oa.lastIndex=t;var r=Oa.exec(e);if(!(r&&r.index<n))break;++l,t=r.index+r[0].length}return{line:l,column:n-t}};e.Token=l,e.tokenize=function(e,t){function r(){return Nt=St,w(),new l}return bt=String(e),_t=bt.length,n(t),s(),g(),r.jumpTo=function(e,n){if(wt=e,xt.locations){Ot=1,Mt=Oa.lastIndex=0;for(var l;(l=Oa.exec(bt))&&l.index<e;)++Ot,Mt=l.index+l[0].length}Pt=!!n,g()},r.current=function(){return new l},"undefined"!=typeof Symbol&&(r[Symbol.iterator]=function(){return{next:function(){var e=r();return{done:e.type===$t,value:e}}}}),r.options=xt,r};var wt,Rt,St,Ct,At,jt,Tt,Lt,Pt,Ot,Mt,Dt,Nt,Bt,Ft,Vt,Ut,qt,Gt,Ht,Xt,Wt=[],Jt={type:"num"},Yt={type:"regexp"},zt={type:"string"},Kt={type:"name"},$t={type:"eof"},Qt={type:"jsxName"},Zt={type:"xjsName"},er={type:"xjsText"},nr={keyword:"break"},lr={keyword:"case",beforeExpr:!0},tr={keyword:"catch"},rr={keyword:"continue"},ar={keyword:"debugger"},or={keyword:"default"},ur={keyword:"do",isLoop:!0},sr={keyword:"else",beforeExpr:!0},ir={keyword:"finally"},cr={keyword:"for",isLoop:!0},dr={keyword:"function"},pr={keyword:"if"},fr={keyword:"return",beforeExpr:!0},gr={keyword:"switch"},hr={keyword:"throw",beforeExpr:!0},mr={keyword:"try"},yr={keyword:"var"},xr={keyword:"let"},br={keyword:"const"},_r={keyword:"while",isLoop:!0},vr={keyword:"with"},Ir={keyword:"new",beforeExpr:!0},Er={keyword:"this"},kr={keyword:"class"},wr={keyword:"extends",beforeExpr:!0},Rr={keyword:"export"},Sr={keyword:"import"},Cr={keyword:"yield",beforeExpr:!0},Ar={keyword:"null",atomValue:null},jr={keyword:"true",atomValue:!0},Tr={keyword:"false",atomValue:!1},Lr={keyword:"in",binop:7,beforeExpr:!0},Pr={"break":nr,"case":lr,"catch":tr,"continue":rr,"debugger":ar,"default":or,"do":ur,"else":sr,"finally":ir,"for":cr,"function":dr,"if":pr,"return":fr,"switch":gr,"throw":hr,"try":mr,"var":yr,let:xr,"const":br,"while":_r,"with":vr,"null":Ar,"true":jr,"false":Tr,"new":Ir,"in":Lr,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:!0},"this":Er,"typeof":{keyword:"typeof",prefix:!0,beforeExpr:!0},"void":{keyword:"void",prefix:!0,beforeExpr:!0},"delete":{keyword:"delete",prefix:!0,beforeExpr:!0},"class":kr,"extends":wr,"export":Rr,"import":Sr,"yield":Cr},Or={type:"[",beforeExpr:!0},Mr={type:"]"},Dr={type:"{",beforeExpr:!0},Nr={type:"}"},Br={type:"(",beforeExpr:!0},Fr={type:")"},Vr={type:",",beforeExpr:!0},Ur={type:";",beforeExpr:!0},qr={type:":",beforeExpr:!0},Gr={type:"."},Hr={type:"?",beforeExpr:!0},Xr={type:"=>",beforeExpr:!0},Wr={type:"template"},Jr={type:"...",beforeExpr:!0},Yr={type:"`"},zr={type:"${",beforeExpr:!0},Kr={type:"jsxText"},$r={type:"::",beforeExpr:!0},Qr={type:"#"},Zr={binop:10,beforeExpr:!0},ea={isAssign:!0,beforeExpr:!0},na={isAssign:!0,beforeExpr:!0},la={postfix:!0,prefix:!0,isUpdate:!0},ta={prefix:!0,beforeExpr:!0},ra={binop:1,beforeExpr:!0},aa={binop:2,beforeExpr:!0},oa={binop:3,beforeExpr:!0},ua={binop:4,beforeExpr:!0},sa={binop:5,beforeExpr:!0},ia={binop:6,beforeExpr:!0},ca={binop:7,beforeExpr:!0},da={binop:8,beforeExpr:!0},pa={binop:9,prefix:!0,beforeExpr:!0},fa={binop:10,beforeExpr:!0},ga={binop:10,beforeExpr:!0},ha={binop:11,beforeExpr:!0,rightAssociative:!0},ma={type:"jsxTagStart"},ya={type:"jsxTagEnd"};e.tokTypes={bracketL:Or,bracketR:Mr,braceL:Dr,braceR:Nr,parenL:Br,parenR:Fr,comma:Vr,semi:Ur,colon:qr,dot:Gr,ellipsis:Jr,question:Hr,slash:Zr,eq:ea,name:Kt,eof:$t,num:Jt,regexp:Yt,string:zt,paamayimNekudotayim:$r,exponent:ha,hash:Qr,arrow:Xr,template:Wr,star:ga,assign:na,backQuote:Yr,dollarBraceL:zr,jsxName:Qt,jsxText:Kr,jsxTagStart:ma,jsxTagEnd:ya};for(var xa in Pr)e.tokTypes["_"+xa]=Pr[xa];var ba=function(e){switch(e.length){case 6:switch(e){case"double":case"export":case"import":case"native":case"public":case"static":case"throws":return!0}return!1;case 4:switch(e){case"byte":case"char":case"enum":case"goto":case"long":return!0}return!1;case 5:switch(e){case"class":case"final":case"float":case"short":case"super":return!0}return!1;case 7:switch(e){case"boolean":case"extends":case"package":case"private":return!0}return!1;case 9:switch(e){case"interface":case"protected":case"transient":return!0}return!1;case 8:switch(e){case"abstract":case"volatile":return!0}return!1;case 10:return"implements"===e;case 3:return"int"===e;case 12:return"synchronized"===e}},_a=function(e){switch(e.length){case 5:switch(e){case"class":case"super":case"const":return!0}return!1;case 6:switch(e){case"export":case"import":return!0}return!1;case 4:return"enum"===e;case 7:return"extends"===e}},va=function(e){switch(e.length){case 9:switch(e){case"interface":case"protected":return!0}return!1;case 7:switch(e){case"package":case"private":return!0}return!1;case 6:switch(e){case"public":case"static":return!0}return!1;case 10:return"implements"===e;case 3:return"let"===e;case 5:return"yield"===e}},Ia=function(e){switch(e){case"eval":case"arguments":return!0}return!1},Ea=function(e){switch(e.length){case 4:switch(e){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return!0}return!1;case 5:switch(e){case"break":case"catch":case"throw":case"while":case"false":return!0}return!1;case 3:switch(e){case"for":case"try":case"var":case"new":return!0}return!1;case 6:switch(e){case"return":case"switch":case"typeof":case"delete":return!0}return!1;case 8:switch(e){case"continue":case"debugger":case"function":return!0}return!1;case 2:switch(e){case"do":case"if":case"in":return!0}return!1;case 7:switch(e){case"default":case"finally":return!0}return!1;case 10:return"instanceof"===e}},ka=function(e){switch(e.length){case 5:switch(e){case"break":case"catch":case"throw":case"while":case"false":case"const":case"class":case"yield":return!0}return!1;case 4:switch(e){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return!0}return!1;case 6:switch(e){case"return":case"switch":case"typeof":case"delete":case"export":case"import":return!0}return!1;case 3:switch(e){case"for":case"try":case"var":case"new":case"let":return!0}return!1;case 8:switch(e){case"continue":case"debugger":case"function":return!0}return!1;case 7:switch(e){case"default":case"finally":case"extends":return!0}return!1;case 2:switch(e){case"do":case"if":case"in":return!0}return!1;case 10:return"instanceof"===e}},wa=Ea,Ra=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,Sa="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",Ca="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_",Aa=new RegExp("["+Sa+"]"),ja=new RegExp("["+Sa+Ca+"]"),Ta=/^\d+$/,La=/^[\da-fA-F]+$/,Pa=/[\n\r\u2028\u2029]/,Oa=/\r\n|[\n\r\u2028\u2029]/g,Ma=e.isIdentifierStart=function(e){return 65>e?36===e:91>e?!0:97>e?95===e:123>e?!0:e>=170&&Aa.test(String.fromCharCode(e))},Da=e.isIdentifierChar=function(e){return 48>e?36===e:58>e?!0:65>e?!1:91>e?!0:97>e?95===e:123>e?!0:e>=170&&ja.test(String.fromCharCode(e))};o.prototype.offset=function(e){return new o(this.line,this.column+e)};var Na={token:"{",isExpr:!1},Ba={token:"{",isExpr:!0},Fa={token:"${",isExpr:!0},Va={token:"(",isExpr:!1},Ua={token:"(",isExpr:!0},qa={token:"`",isExpr:!0},Ga={token:"function",isExpr:!0},Ha={token:"<tag",isExpr:!1},Xa={token:"</tag",isExpr:!1},Wa={token:"<tag>...</tag>",isExpr:!0},Ja=!1;try{new RegExp("","u"),Ja=!0}catch(Ya){}var za,Ka={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:"♦"},Ka={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:"♦"};e.Node=W;var $a={kind:"loop"},Qa={kind:"switch"}})},{}],121:[function(e){var n=e("../lib/types"),l=n.Type,t=l.def,r=l.or,a=n.builtInTypes,o=a.string,u=a.number,s=a.boolean,i=a.RegExp,c=e("../lib/shared"),d=c.defaults,p=c.geq;t("Printable").field("loc",r(t("SourceLocation"),null),d["null"],!0),t("Node").bases("Printable").field("type",o).field("comments",r([t("Comment")],null),d["null"],!0),t("SourceLocation").build("start","end","source").field("start",t("Position")).field("end",t("Position")).field("source",r(o,null),d["null"]),t("Position").build("line","column").field("line",p(1)).field("column",p(0)),t("Program").bases("Node").build("body").field("body",[t("Statement")]),t("Function").bases("Node").field("id",r(t("Identifier"),null),d["null"]).field("params",[t("Pattern")]).field("body",r(t("BlockStatement"),t("Expression"))),t("Statement").bases("Node"),t("EmptyStatement").bases("Statement").build(),t("BlockStatement").bases("Statement").build("body").field("body",[t("Statement")]),t("ExpressionStatement").bases("Statement").build("expression").field("expression",t("Expression")),t("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",t("Expression")).field("consequent",t("Statement")).field("alternate",r(t("Statement"),null),d["null"]),t("LabeledStatement").bases("Statement").build("label","body").field("label",t("Identifier")).field("body",t("Statement")),t("BreakStatement").bases("Statement").build("label").field("label",r(t("Identifier"),null),d["null"]),t("ContinueStatement").bases("Statement").build("label").field("label",r(t("Identifier"),null),d["null"]),t("WithStatement").bases("Statement").build("object","body").field("object",t("Expression")).field("body",t("Statement")),t("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",t("Expression")).field("cases",[t("SwitchCase")]).field("lexical",s,d["false"]),t("ReturnStatement").bases("Statement").build("argument").field("argument",r(t("Expression"),null)),t("ThrowStatement").bases("Statement").build("argument").field("argument",t("Expression")),t("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",t("BlockStatement")).field("handler",r(t("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[t("CatchClause")],function(){return this.handler?[this.handler]:[]},!0).field("guardedHandlers",[t("CatchClause")],d.emptyArray).field("finalizer",r(t("BlockStatement"),null),d["null"]),t("CatchClause").bases("Node").build("param","guard","body").field("param",t("Pattern")).field("guard",r(t("Expression"),null),d["null"]).field("body",t("BlockStatement")),t("WhileStatement").bases("Statement").build("test","body").field("test",t("Expression")).field("body",t("Statement")),t("DoWhileStatement").bases("Statement").build("body","test").field("body",t("Statement")).field("test",t("Expression")),t("ForStatement").bases("Statement").build("init","test","update","body").field("init",r(t("VariableDeclaration"),t("Expression"),null)).field("test",r(t("Expression"),null)).field("update",r(t("Expression"),null)).field("body",t("Statement")),t("ForInStatement").bases("Statement").build("left","right","body","each").field("left",r(t("VariableDeclaration"),t("Expression"))).field("right",t("Expression")).field("body",t("Statement")).field("each",s),t("DebuggerStatement").bases("Statement").build(),t("Declaration").bases("Statement"),t("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",t("Identifier")),t("FunctionExpression").bases("Function","Expression").build("id","params","body"),t("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",r("var","let","const")).field("declarations",[r(t("VariableDeclarator"),t("Identifier"))]),t("VariableDeclarator").bases("Node").build("id","init").field("id",t("Pattern")).field("init",r(t("Expression"),null)),t("Expression").bases("Node","Pattern"),t("ThisExpression").bases("Expression").build(),t("ArrayExpression").bases("Expression").build("elements").field("elements",[r(t("Expression"),null)]),t("ObjectExpression").bases("Expression").build("properties").field("properties",[t("Property")]),t("Property").bases("Node").build("kind","key","value").field("kind",r("init","get","set")).field("key",r(t("Literal"),t("Identifier"))).field("value",t("Expression")),t("SequenceExpression").bases("Expression").build("expressions").field("expressions",[t("Expression")]);var f=r("-","+","!","~","typeof","void","delete");t("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",f).field("argument",t("Expression")).field("prefix",s,d["true"]);var g=r("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");t("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",g).field("left",t("Expression")).field("right",t("Expression"));var h=r("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");t("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",h).field("left",t("Pattern")).field("right",t("Expression"));var m=r("++","--");t("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",m).field("argument",t("Expression")).field("prefix",s);var y=r("||","&&");t("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",y).field("left",t("Expression")).field("right",t("Expression")),t("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",t("Expression")).field("consequent",t("Expression")).field("alternate",t("Expression")),t("NewExpression").bases("Expression").build("callee","arguments").field("callee",t("Expression")).field("arguments",[t("Expression")]),t("CallExpression").bases("Expression").build("callee","arguments").field("callee",t("Expression")).field("arguments",[t("Expression")]),t("MemberExpression").bases("Expression").build("object","property","computed").field("object",t("Expression")).field("property",r(t("Identifier"),t("Expression"))).field("computed",s),t("Pattern").bases("Node"),t("ObjectPattern").bases("Pattern").build("properties").field("properties",[t("PropertyPattern")]),t("PropertyPattern").bases("Pattern").build("key","pattern").field("key",r(t("Literal"),t("Identifier"))).field("pattern",t("Pattern")),t("ArrayPattern").bases("Pattern").build("elements").field("elements",[r(t("Pattern"),null)]),t("SwitchCase").bases("Node").build("test","consequent").field("test",r(t("Expression"),null)).field("consequent",[t("Statement")]),t("Identifier").bases("Node","Expression","Pattern").build("name").field("name",o),t("Literal").bases("Node","Expression").build("value").field("value",r(o,s,null,u,i)),t("Comment").bases("Printable").field("value",o).field("leading",s,d["true"]).field("trailing",s,d["false"]),t("Block").bases("Comment").build("value","leading","trailing"),t("Line").bases("Comment").build("value","leading","trailing")},{"../lib/shared":132,"../lib/types":133}],122:[function(e){e("./core");var n=e("../lib/types"),l=n.Type.def,t=n.Type.or,r=n.builtInTypes,a=r.string,o=r.boolean;l("XMLDefaultDeclaration").bases("Declaration").field("namespace",l("Expression")),l("XMLAnyName").bases("Expression"),l("XMLQualifiedIdentifier").bases("Expression").field("left",t(l("Identifier"),l("XMLAnyName"))).field("right",t(l("Identifier"),l("Expression"))).field("computed",o),l("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",t(l("Identifier"),l("Expression"))).field("computed",o),l("XMLAttributeSelector").bases("Expression").field("attribute",l("Expression")),l("XMLFilterExpression").bases("Expression").field("left",l("Expression")).field("right",l("Expression")),l("XMLElement").bases("XML","Expression").field("contents",[l("XML")]),l("XMLList").bases("XML","Expression").field("contents",[l("XML")]),l("XML").bases("Node"),l("XMLEscape").bases("XML").field("expression",l("Expression")),l("XMLText").bases("XML").field("text",a),l("XMLStartTag").bases("XML").field("contents",[l("XML")]),l("XMLEndTag").bases("XML").field("contents",[l("XML")]),l("XMLPointTag").bases("XML").field("contents",[l("XML")]),l("XMLName").bases("XML").field("contents",t(a,[l("XML")])),l("XMLAttribute").bases("XML").field("value",a),l("XMLCdata").bases("XML").field("contents",a),l("XMLComment").bases("XML").field("contents",a),l("XMLProcessingInstruction").bases("XML").field("target",a).field("contents",t(a,null))},{"../lib/types":133,"./core":121}],123:[function(e){e("./core");var n=e("../lib/types"),l=n.Type.def,t=n.Type.or,r=n.builtInTypes,a=r.boolean,o=(r.object,r.string),u=e("../lib/shared").defaults;l("Function").field("generator",a,u["false"]).field("expression",a,u["false"]).field("defaults",[t(l("Expression"),null)],u.emptyArray).field("rest",t(l("Identifier"),null),u["null"]),l("FunctionDeclaration").build("id","params","body","generator","expression"),l("FunctionExpression").build("id","params","body","generator","expression"),l("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,u["null"]).field("generator",!1),l("YieldExpression").bases("Expression").build("argument","delegate").field("argument",t(l("Expression"),null)).field("delegate",a,u["false"]),l("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",l("Expression")).field("blocks",[l("ComprehensionBlock")]).field("filter",t(l("Expression"),null)),l("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",l("Expression")).field("blocks",[l("ComprehensionBlock")]).field("filter",t(l("Expression"),null)),l("ComprehensionBlock").bases("Node").build("left","right","each").field("left",l("Pattern")).field("right",l("Expression")).field("each",a),l("ModuleSpecifier").bases("Literal").build("value").field("value",o),l("Property").field("key",t(l("Literal"),l("Identifier"),l("Expression"))).field("method",a,u["false"]).field("shorthand",a,u["false"]).field("computed",a,u["false"]),l("PropertyPattern").field("key",t(l("Literal"),l("Identifier"),l("Expression"))).field("computed",a,u["false"]),l("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",t("init","get","set","")).field("key",t(l("Literal"),l("Identifier"),l("Expression"))).field("value",l("Function")).field("computed",a,u["false"]),l("SpreadElement").bases("Node").build("argument").field("argument",l("Expression")),l("ArrayExpression").field("elements",[t(l("Expression"),l("SpreadElement"),null)]),l("NewExpression").field("arguments",[t(l("Expression"),l("SpreadElement"))]),l("CallExpression").field("arguments",[t(l("Expression"),l("SpreadElement"))]),l("SpreadElementPattern").bases("Pattern").build("argument").field("argument",l("Pattern"));
var s=t(l("MethodDefinition"),l("VariableDeclarator"),l("ClassPropertyDefinition"),l("ClassProperty"));l("ClassProperty").bases("Declaration").build("key").field("key",t(l("Literal"),l("Identifier"),l("Expression"))).field("computed",a,u["false"]),l("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",s),l("ClassBody").bases("Declaration").build("body").field("body",[s]),l("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",l("Identifier")).field("body",l("ClassBody")).field("superClass",t(l("Expression"),null),u["null"]),l("ClassExpression").bases("Expression").build("id","body","superClass").field("id",t(l("Identifier"),null),u["null"]).field("body",l("ClassBody")).field("superClass",t(l("Expression"),null),u["null"]).field("implements",[l("ClassImplements")],u.emptyArray),l("ClassImplements").bases("Node").build("id").field("id",l("Identifier")).field("superClass",t(l("Expression"),null),u["null"]),l("Specifier").bases("Node"),l("NamedSpecifier").bases("Specifier").field("id",l("Identifier")).field("name",t(l("Identifier"),null),u["null"]),l("ExportSpecifier").bases("NamedSpecifier").build("id","name"),l("ExportBatchSpecifier").bases("Specifier").build(),l("ImportSpecifier").bases("NamedSpecifier").build("id","name"),l("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",l("Identifier")),l("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",l("Identifier")),l("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",a).field("declaration",t(l("Declaration"),l("Expression"),null)).field("specifiers",[t(l("ExportSpecifier"),l("ExportBatchSpecifier"))],u.emptyArray).field("source",t(l("ModuleSpecifier"),null),u["null"]),l("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[t(l("ImportSpecifier"),l("ImportNamespaceSpecifier"),l("ImportDefaultSpecifier"))],u.emptyArray).field("source",l("ModuleSpecifier")),l("TaggedTemplateExpression").bases("Expression").field("tag",l("Expression")).field("quasi",l("TemplateLiteral")),l("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[l("TemplateElement")]).field("expressions",[l("Expression")]),l("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:o,raw:o}).field("tail",a)},{"../lib/shared":132,"../lib/types":133,"./core":121}],124:[function(e){e("./core");var n=e("../lib/types"),l=n.Type.def,t=n.Type.or,r=n.builtInTypes,a=r.boolean,o=e("../lib/shared").defaults;l("Function").field("async",a,o["false"]),l("SpreadProperty").bases("Node").build("argument").field("argument",l("Expression")),l("ObjectExpression").field("properties",[t(l("Property"),l("SpreadProperty"))]),l("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",l("Pattern")),l("ObjectPattern").field("properties",[t(l("PropertyPattern"),l("SpreadPropertyPattern"))]),l("AwaitExpression").bases("Expression").build("argument","all").field("argument",t(l("Expression"),null)).field("all",a,o["false"])},{"../lib/shared":132,"../lib/types":133,"./core":121}],125:[function(e){e("./core");var n=e("../lib/types"),l=n.Type.def,t=n.Type.or,r=n.builtInTypes,a=r.string,o=r.boolean,u=e("../lib/shared").defaults;l("XJSAttribute").bases("Node").build("name","value").field("name",t(l("XJSIdentifier"),l("XJSNamespacedName"))).field("value",t(l("Literal"),l("XJSExpressionContainer"),null),u["null"]),l("XJSIdentifier").bases("Node").build("name").field("name",a),l("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",l("XJSIdentifier")).field("name",l("XJSIdentifier")),l("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",t(l("XJSIdentifier"),l("XJSMemberExpression"))).field("property",l("XJSIdentifier")).field("computed",o,u.false);var s=t(l("XJSIdentifier"),l("XJSNamespacedName"),l("XJSMemberExpression"));l("XJSSpreadAttribute").bases("Node").build("argument").field("argument",l("Expression"));var i=[t(l("XJSAttribute"),l("XJSSpreadAttribute"))];l("XJSExpressionContainer").bases("Expression").build("expression").field("expression",l("Expression")),l("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",l("XJSOpeningElement")).field("closingElement",t(l("XJSClosingElement"),null),u["null"]).field("children",[t(l("XJSElement"),l("XJSExpressionContainer"),l("XJSText"),l("Literal"))],u.emptyArray).field("name",s,function(){return this.openingElement.name}).field("selfClosing",o,function(){return this.openingElement.selfClosing}).field("attributes",i,function(){return this.openingElement.attributes}),l("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",s).field("attributes",i,u.emptyArray).field("selfClosing",o,u["false"]),l("XJSClosingElement").bases("Node").build("name").field("name",s),l("XJSText").bases("Literal").build("value").field("value",a),l("XJSEmptyExpression").bases("Expression").build(),l("Type").bases("Node"),l("AnyTypeAnnotation").bases("Type"),l("VoidTypeAnnotation").bases("Type"),l("NumberTypeAnnotation").bases("Type"),l("StringTypeAnnotation").bases("Type"),l("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",a).field("raw",a),l("BooleanTypeAnnotation").bases("Type"),l("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",l("Type")),l("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",l("Type")),l("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[l("FunctionTypeParam")]).field("returnType",l("Type")).field("rest",t(l("FunctionTypeParam"),null)).field("typeParameters",t(l("TypeParameterDeclaration"),null)),l("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",l("Identifier")).field("typeAnnotation",l("Type")).field("optional",o),l("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",l("Type")),l("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[l("ObjectTypeProperty")]).field("indexers",[l("ObjectTypeIndexer")],u.emptyArray).field("callProperties",[l("ObjectTypeCallProperty")],u.emptyArray),l("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",t(l("Literal"),l("Identifier"))).field("value",l("Type")).field("optional",o),l("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",l("Identifier")).field("key",l("Type")).field("value",l("Type")),l("ObjectTypeCallProperty").bases("Node").build("value").field("value",l("FunctionTypeAnnotation")).field("static",o,!1),l("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",t(l("Identifier"),l("QualifiedTypeIdentifier"))).field("id",l("Identifier")),l("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",t(l("Identifier"),l("QualifiedTypeIdentifier"))).field("typeParameters",t(l("TypeParameterInstantiation"),null)),l("MemberTypeAnnotation").bases("Type").build("object","property").field("object",l("Identifier")).field("property",t(l("MemberTypeAnnotation"),l("GenericTypeAnnotation"))),l("UnionTypeAnnotation").bases("Type").build("types").field("types",[l("Type")]),l("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[l("Type")]),l("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",l("Type")),l("Identifier").field("typeAnnotation",t(l("TypeAnnotation"),null),u["null"]),l("TypeParameterDeclaration").bases("Node").build("params").field("params",[l("Identifier")]),l("TypeParameterInstantiation").bases("Node").build("params").field("params",[l("Type")]),l("Function").field("returnType",t(l("TypeAnnotation"),null),u["null"]).field("typeParameters",t(l("TypeParameterDeclaration"),null),u["null"]),l("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",l("TypeAnnotation")).field("static",o,!1),l("ClassImplements").field("typeParameters",t(l("TypeParameterInstantiation"),null),u["null"]),l("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",l("Identifier")).field("typeParameters",t(l("TypeParameterDeclaration"),null),u["null"]).field("body",l("ObjectTypeAnnotation")).field("extends",[l("InterfaceExtends")]),l("InterfaceExtends").bases("Node").build("id").field("id",l("Identifier")).field("typeParameters",t(l("TypeParameterInstantiation"),null)),l("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",l("Identifier")).field("typeParameters",t(l("TypeParameterDeclaration"),null)).field("right",l("Type")),l("TypeCastExpression").bases("Expression").build("expression","typeAnnotation").field("expression",l("Expression")).field("typeAnnotation",l("TypeAnnotation")),l("TupleTypeAnnotation").bases("Type").build("types").field("types",[l("Type")]),l("DeclareVariable").bases("Statement").build("id").field("id",l("Identifier")),l("DeclareFunction").bases("Statement").build("id").field("id",l("Identifier")),l("DeclareClass").bases("InterfaceDeclaration").build("id"),l("DeclareModule").bases("Statement").build("id","body").field("id",t(l("Identifier"),l("Literal"))).field("body",l("BlockStatement"))},{"../lib/shared":132,"../lib/types":133,"./core":121}],126:[function(e){e("./core");var n=e("../lib/types"),l=n.Type.def,t=n.Type.or,r=e("../lib/shared").geq;l("ForOfStatement").bases("Statement").build("left","right","body").field("left",t(l("VariableDeclaration"),l("Expression"))).field("right",l("Expression")).field("body",l("Statement")),l("LetStatement").bases("Statement").build("head","body").field("head",[l("VariableDeclarator")]).field("body",l("Statement")),l("LetExpression").bases("Expression").build("head","body").field("head",[l("VariableDeclarator")]).field("body",l("Expression")),l("GraphExpression").bases("Expression").build("index","expression").field("index",r(0)).field("expression",l("Literal")),l("GraphIndexExpression").bases("Expression").build("index").field("index",r(0))},{"../lib/shared":132,"../lib/types":133,"./core":121}],127:[function(e,n){function l(e,n,l){return d.check(l)?l.length=0:l=null,r(e,n,l)}function t(e){return/[_$a-z][_$a-z0-9]*/i.test(e)?"."+e:"["+JSON.stringify(e)+"]"}function r(e,n,l){return e===n?!0:d.check(e)?a(e,n,l):p.check(e)?o(e,n,l):f.check(e)?f.check(n)&&+e===+n:g.check(e)?g.check(n)&&e.source===n.source&&e.global===n.global&&e.multiline===n.multiline&&e.ignoreCase===n.ignoreCase:e==n}function a(e,n,l){d.assert(e);var t=e.length;if(!d.check(n)||n.length!==t)return l&&l.push("length"),!1;for(var a=0;t>a;++a){if(l&&l.push(a),a in e!=a in n)return!1;if(!r(e[a],n[a],l))return!1;l&&u.strictEqual(l.pop(),a)}return!0}function o(e,n,l){if(p.assert(e),!p.check(n))return!1;if(e.type!==n.type)return l&&l.push("type"),!1;var t=i(e),a=t.length,o=i(n),s=o.length;if(a===s){for(var d=0;a>d;++d){var f=t[d],g=c(e,f),m=c(n,f);if(l&&l.push(f),!r(g,m,l))return!1;l&&u.strictEqual(l.pop(),f)}return!0}if(!l)return!1;var y=Object.create(null);for(d=0;a>d;++d)y[t[d]]=!0;for(d=0;s>d;++d){if(f=o[d],!h.call(y,f))return l.push(f),!1;delete y[f]}for(f in y){l.push(f);break}return!1}var u=e("assert"),s=e("../main"),i=s.getFieldNames,c=s.getFieldValue,d=s.builtInTypes.array,p=s.builtInTypes.object,f=s.builtInTypes.Date,g=s.builtInTypes.RegExp,h=Object.prototype.hasOwnProperty;l.assert=function(e,n){var r=[];l(e,n,r)||(0===r.length?u.strictEqual(e,n):u.ok(!1,"Nodes differ in the following path: "+r.map(t).join("")))},n.exports=l},{"../main":134,assert:136}],128:[function(e,n){function l(e,n,t){s.ok(this instanceof l),g.call(this,e,n,t)}function t(e){return c.BinaryExpression.check(e)||c.LogicalExpression.check(e)}function r(e){return c.CallExpression.check(e)?!0:f.check(e)?e.some(r):c.Node.check(e)?i.someField(e,function(e,n){return r(n)}):!1}function a(e){for(var n,l;e.parent;e=e.parent){if(n=e.node,l=e.parent.node,c.BlockStatement.check(l)&&"body"===e.parent.name&&0===e.name)return s.strictEqual(l.body[0],n),!0;if(c.ExpressionStatement.check(l)&&"expression"===e.name)return s.strictEqual(l.expression,n),!0;if(c.SequenceExpression.check(l)&&"expressions"===e.parent.name&&0===e.name)s.strictEqual(l.expressions[0],n);else if(c.CallExpression.check(l)&&"callee"===e.name)s.strictEqual(l.callee,n);else if(c.MemberExpression.check(l)&&"object"===e.name)s.strictEqual(l.object,n);else if(c.ConditionalExpression.check(l)&&"test"===e.name)s.strictEqual(l.test,n);else if(t(l)&&"left"===e.name)s.strictEqual(l.left,n);else{if(!c.UnaryExpression.check(l)||l.prefix||"argument"!==e.name)return!1;s.strictEqual(l.argument,n)}}return!0}function o(e){if(c.VariableDeclaration.check(e.node)){var n=e.get("declarations").value;if(!n||0===n.length)return e.prune()}else if(c.ExpressionStatement.check(e.node)){if(!e.get("expression").value)return e.prune()}else c.IfStatement.check(e.node)&&u(e);return e}function u(e){var n=e.get("test").value,l=e.get("alternate").value,t=e.get("consequent").value;if(t||l){if(!t&&l){var r=d.unaryExpression("!",n,!0);c.UnaryExpression.check(n)&&"!"===n.operator&&(r=n.argument),e.get("test").replace(r),e.get("consequent").replace(l),e.get("alternate").replace()}}else{var a=d.expressionStatement(n);e.replace(a)}}var s=e("assert"),i=e("./types"),c=i.namedTypes,d=i.builders,p=i.builtInTypes.number,f=i.builtInTypes.array,g=e("./path"),h=e("./scope");e("util").inherits(l,g);var m=l.prototype;Object.defineProperties(m,{node:{get:function(){return Object.defineProperty(this,"node",{configurable:!0,value:this._computeNode()}),this.node}},parent:{get:function(){return Object.defineProperty(this,"parent",{configurable:!0,value:this._computeParent()}),this.parent}},scope:{get:function(){return Object.defineProperty(this,"scope",{configurable:!0,value:this._computeScope()}),this.scope}}}),m.replace=function(){return delete this.node,delete this.parent,delete this.scope,g.prototype.replace.apply(this,arguments)},m.prune=function(){var e=this.parent;return this.replace(),o(e)},m._computeNode=function(){var e=this.value;if(c.Node.check(e))return e;var n=this.parentPath;return n&&n.node||null},m._computeParent=function(){var e=this.value,n=this.parentPath;if(!c.Node.check(e)){for(;n&&!c.Node.check(n.value);)n=n.parentPath;n&&(n=n.parentPath)}for(;n&&!c.Node.check(n.value);)n=n.parentPath;return n||null},m._computeScope=function(){var e=this.value,n=this.parentPath,l=n&&n.scope;return c.Node.check(e)&&h.isEstablishedBy(e)&&(l=new h(this,l)),l||null},m.getValueProperty=function(e){return i.getFieldValue(this.value,e)},m.needsParens=function(e){var n=this.parentPath;if(!n)return!1;var l=this.value;if(!c.Expression.check(l))return!1;if("Identifier"===l.type)return!1;for(;!c.Node.check(n.value);)if(n=n.parentPath,!n)return!1;var t=n.value;switch(l.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return"MemberExpression"===t.type&&"object"===this.name&&t.object===l;case"BinaryExpression":case"LogicalExpression":switch(t.type){case"CallExpression":return"callee"===this.name&&t.callee===l;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return!0;case"MemberExpression":return"object"===this.name&&t.object===l;case"BinaryExpression":case"LogicalExpression":var a=t.operator,n=y[a],o=l.operator,u=y[o];if(n>u)return!0;if(n===u&&"right"===this.name)return s.strictEqual(t.right,l),!0;default:return!1}case"SequenceExpression":switch(t.type){case"ForStatement":return!1;case"ExpressionStatement":return"expression"!==this.name;default:return!0}case"YieldExpression":switch(t.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return!0;default:return!1}case"Literal":return"MemberExpression"===t.type&&p.check(l.value)&&"object"===this.name&&t.object===l;case"AssignmentExpression":case"ConditionalExpression":switch(t.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return!0;case"CallExpression":return"callee"===this.name&&t.callee===l;case"ConditionalExpression":return"test"===this.name&&t.test===l;case"MemberExpression":return"object"===this.name&&t.object===l;default:return!1}default:if("NewExpression"===t.type&&"callee"===this.name&&t.callee===l)return r(l)}return e!==!0&&!this.canBeFirstInStatement()&&this.firstInStatement()?!0:!1};var y={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,n){e.forEach(function(e){y[e]=n})}),m.canBeFirstInStatement=function(){var e=this.node;return!c.FunctionExpression.check(e)&&!c.ObjectExpression.check(e)},m.firstInStatement=function(){return a(this)},n.exports=l},{"./path":130,"./scope":131,"./types":133,assert:136,util:161}],129:[function(e,n){function l(){s.ok(this instanceof l),this._reusableContextStack=[],this._methodNameTable=t(this),this.Context=o(this),this._visiting=!1,this._changeReported=!1}function t(e){var n=Object.create(null);for(var l in e)/^visit[A-Z]/.test(l)&&(n[l.slice("visit".length)]=!0);for(var t=i.computeSupertypeLookupTable(n),r=Object.create(null),n=Object.keys(t),a=n.length,o=0;a>o;++o){var u=n[o];l="visit"+t[u],g.check(e[l])&&(r[u]=l)}return r}function r(e,n){for(var l in n)h.call(n,l)&&(e[l]=n[l]);return e}function a(e,n){s.ok(e instanceof c),s.ok(n instanceof l);var t=e.value;if(p.check(t))e.each(n.visitWithoutReset,n);else if(f.check(t)){for(var r=i.getFieldNames(t),a=r.length,o=[],u=0;a>u;++u){var d=r[u];h.call(t,d)||(t[d]=i.getFieldValue(t,d)),o.push(e.get(d))}for(var u=0;a>u;++u)n.visitWithoutReset(o[u])}else;return e.value}function o(e){function n(t){s.ok(this instanceof n),s.ok(this instanceof l),s.ok(t instanceof c),Object.defineProperty(this,"visitor",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.currentPath=t,this.needToCallTraverse=!0,Object.seal(this)}s.ok(e instanceof l);var t=n.prototype=Object.create(e);return t.constructor=n,r(t,x),n}var u,s=e("assert"),i=e("./types"),c=e("./node-path"),d=i.namedTypes.Node,p=i.builtInTypes.array,f=i.builtInTypes.object,g=i.builtInTypes.function,h=Object.prototype.hasOwnProperty;l.fromMethodsObject=function(e){function n(){s.ok(this instanceof n),l.call(this)}if(e instanceof l)return e;if(!f.check(e))return new l;var t=n.prototype=Object.create(m);return t.constructor=n,r(t,e),r(n,l),g.assert(n.fromMethodsObject),g.assert(n.visit),new n},l.visit=function(e,n){return l.fromMethodsObject(n).visit(e)};var m=l.prototype,y=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");m.visit=function(){s.ok(!this._visiting,y),this._visiting=!0,this._changeReported=!1;for(var e=arguments.length,n=new Array(e),l=0;e>l;++l)n[l]=arguments[l];n[0]instanceof c||(n[0]=new c({root:n[0]}).get("root")),this.reset.apply(this,n);try{return this.visitWithoutReset(n[0])}finally{this._visiting=!1}},m.reset=function(){},m.visitWithoutReset=function(e){if(this instanceof this.Context)return this.visitor.visitWithoutReset(e);s.ok(e instanceof c);var n=e.value,l=d.check(n)&&this._methodNameTable[n.type];if(!l)return a(e,this);var t=this.acquireContext(e);try{return t.invokeVisitorMethod(l)}finally{this.releaseContext(t)}},m.acquireContext=function(e){return 0===this._reusableContextStack.length?new this.Context(e):this._reusableContextStack.pop().reset(e)},m.releaseContext=function(e){s.ok(e instanceof this.Context),this._reusableContextStack.push(e),e.currentPath=null},m.reportChanged=function(){this._changeReported=!0},m.wasChangeReported=function(){return this._changeReported};var x=Object.create(null);x.reset=function(e){return s.ok(this instanceof this.Context),s.ok(e instanceof c),this.currentPath=e,this.needToCallTraverse=!0,this},x.invokeVisitorMethod=function(e){s.ok(this instanceof this.Context),s.ok(this.currentPath instanceof c);var n=this.visitor[e].call(this,this.currentPath);n===!1?this.needToCallTraverse=!1:n!==u&&(this.currentPath=this.currentPath.replace(n)[0],this.needToCallTraverse&&this.traverse(this.currentPath)),s.strictEqual(this.needToCallTraverse,!1,"Must either call this.traverse or return false in "+e);var l=this.currentPath;return l&&l.value},x.traverse=function(e,n){return s.ok(this instanceof this.Context),s.ok(e instanceof c),s.ok(this.currentPath instanceof c),this.needToCallTraverse=!1,a(e,l.fromMethodsObject(n||this.visitor))},x.visit=function(e,n){return s.ok(this instanceof this.Context),s.ok(e instanceof c),s.ok(this.currentPath instanceof c),this.needToCallTraverse=!1,l.fromMethodsObject(n||this.visitor).visitWithoutReset(e)},x.reportChanged=function(){this.visitor.reportChanged()},n.exports=l},{"./node-path":128,"./types":133,assert:136}],130:[function(e,n){function l(e,n,t){s.ok(this instanceof l),n?s.ok(n instanceof l):(n=null,t=null),this.value=e,this.parentPath=n,this.name=t,this.__childCache=null}function t(e){return e.__childCache||(e.__childCache=Object.create(null))}function r(e,n){var l=t(e),r=e.getValueProperty(n),a=l[n];return c.call(l,n)&&a.value===r||(a=l[n]=new e.constructor(r,e,n)),a}function a(){}function o(e,n,l,r){if(p.assert(e.value),0===n)return a;var o=e.value.length;if(1>o)return a;var u=arguments.length;2===u?(l=0,r=o):3===u?(l=Math.max(l,0),r=o):(l=Math.max(l,0),r=Math.min(r,o)),f.assert(l),f.assert(r);for(var i=Object.create(null),d=t(e),g=l;r>g;++g)if(c.call(e.value,g)){var h=e.get(g);s.strictEqual(h.name,g);var m=g+n;h.name=m,i[m]=h,delete d[g]}return delete d.length,function(){for(var n in i){var l=i[n];s.strictEqual(l.name,+n),d[n]=l,e.value[n]=l.value}}}function u(e){s.ok(e instanceof l);var n=e.parentPath;if(!n)return e;var r=n.value,a=t(n);if(r[e.name]===e.value)a[e.name]=e;else if(p.check(r)){var o=r.indexOf(e.value);o>=0&&(a[e.name=o]=e)}else r[e.name]=e.value,a[e.name]=e;return s.strictEqual(r[e.name],e.value),s.strictEqual(e.parentPath.get(e.name),e),e}var s=e("assert"),i=Object.prototype,c=i.hasOwnProperty,d=e("./types"),p=d.builtInTypes.array,f=d.builtInTypes.number,g=Array.prototype,h=(g.slice,g.map,l.prototype);h.getValueProperty=function(e){return this.value[e]},h.get=function(){for(var e=this,n=arguments,l=n.length,t=0;l>t;++t)e=r(e,n[t]);return e},h.each=function(e,n){for(var l=[],t=this.value.length,r=0,r=0;t>r;++r)c.call(this.value,r)&&(l[r]=this.get(r));for(n=n||this,r=0;t>r;++r)c.call(l,r)&&e.call(n,l[r])},h.map=function(e,n){var l=[];return this.each(function(n){l.push(e.call(this,n))},n),l},h.filter=function(e,n){var l=[];return this.each(function(n){e.call(this,n)&&l.push(n)},n),l},h.shift=function(){var e=o(this,-1),n=this.value.shift();return e(),n},h.unshift=function(){var e=o(this,arguments.length),n=this.value.unshift.apply(this.value,arguments);return e(),n},h.push=function(){return p.assert(this.value),delete t(this).length,this.value.push.apply(this.value,arguments)},h.pop=function(){p.assert(this.value);var e=t(this);return delete e[this.value.length-1],delete e.length,this.value.pop()},h.insertAt=function(e){var n=arguments.length,l=o(this,n-1,e);if(l===a)return this;e=Math.max(e,0);for(var t=1;n>t;++t)this.value[e+t-1]=arguments[t];return l(),this},h.insertBefore=function(){for(var e=this.parentPath,n=arguments.length,l=[this.name],t=0;n>t;++t)l.push(arguments[t]);return e.insertAt.apply(e,l)},h.insertAfter=function(){for(var e=this.parentPath,n=arguments.length,l=[this.name+1],t=0;n>t;++t)l.push(arguments[t]);return e.insertAt.apply(e,l)},h.replace=function(e){var n=[],l=this.parentPath.value,r=t(this.parentPath),a=arguments.length;if(u(this),p.check(l)){for(var i=l.length,c=o(this.parentPath,a-1,this.name+1),d=[this.name,1],f=0;a>f;++f)d.push(arguments[f]);var g=l.splice.apply(l,d);if(s.strictEqual(g[0],this.value),s.strictEqual(l.length,i-1+a),c(),0===a)delete this.value,delete r[this.name],this.__childCache=null;else{for(s.strictEqual(l[this.name],e),this.value!==e&&(this.value=e,this.__childCache=null),f=0;a>f;++f)n.push(this.parentPath.get(this.name+f));s.strictEqual(n[0],this)}}else 1===a?(this.value!==e&&(this.__childCache=null),this.value=l[this.name]=e,n.push(this)):0===a?(delete l[this.name],delete this.value,this.__childCache=null):s.ok(!1,"Could not replace path");return n},n.exports=l},{"./types":133,assert:136}],131:[function(e,n){function l(n,t){u.ok(this instanceof l),u.ok(n instanceof e("./node-path")),y.assert(n.value);var r;t?(u.ok(t instanceof l),r=t.depth+1):(t=null,r=0),Object.defineProperties(this,{path:{value:n},node:{value:n.value},isGlobal:{value:!t,enumerable:!0},depth:{value:r},parent:{value:t},bindings:{value:{}}})}function t(e,n){var l=e.value;y.assert(l),c.CatchClause.check(l)?o(e.get("param"),n):r(e,n)}function r(e,n){var l=e.value;e.parent&&c.FunctionExpression.check(e.parent.node)&&e.parent.node.id&&o(e.parent.get("id"),n),l&&(f.check(l)?e.each(function(e){a(e,n)}):c.Function.check(l)?(e.get("params").each(function(e){o(e,n)}),a(e.get("body"),n)):c.VariableDeclarator.check(l)?(o(e.get("id"),n),a(e.get("init"),n)):"ImportSpecifier"===l.type||"ImportNamespaceSpecifier"===l.type||"ImportDefaultSpecifier"===l.type?o(e.get(l.name?"name":"id"),n):d.check(l)&&!p.check(l)&&s.eachField(l,function(l,t){var r=e.get(l);u.strictEqual(r.value,t),a(r,n)}))}function a(e,n){var l=e.value;if(!l||p.check(l));else if(c.FunctionDeclaration.check(l))o(e.get("id"),n);else if(c.ClassDeclaration&&c.ClassDeclaration.check(l))o(e.get("id"),n);else if(y.check(l)){if(c.CatchClause.check(l)){var t=l.param.name,a=g.call(n,t);r(e.get("body"),n),a||delete n[t]}}else r(e,n)}function o(e,n){var l=e.value;c.Pattern.assert(l),c.Identifier.check(l)?g.call(n,l.name)?n[l.name].push(e):n[l.name]=[e]:c.SpreadElement&&c.SpreadElement.check(l)&&o(e.get("argument"),n)}var u=e("assert"),s=e("./types"),i=s.Type,c=s.namedTypes,d=c.Node,p=c.Expression,f=s.builtInTypes.array,g=Object.prototype.hasOwnProperty,h=s.builders,m=[c.Program,c.Function,c.CatchClause],y=i.or.apply(i,m);l.isEstablishedBy=function(e){return y.check(e)};var x=l.prototype;x.didScan=!1,x.declares=function(e){return this.scan(),g.call(this.bindings,e)},x.declareTemporary=function(e){e?u.ok(/^[a-z$_]/i.test(e),e):e="t$",e+=this.depth.toString(36)+"$",this.scan();for(var n=0;this.declares(e+n);)++n;var l=e+n;return this.bindings[l]=s.builders.identifier(l)},x.injectTemporary=function(e,n){e||(e=this.declareTemporary());var l=this.path.get("body");return c.BlockStatement.check(l.value)&&(l=l.get("body")),l.unshift(h.variableDeclaration("var",[h.variableDeclarator(e,n||null)])),e},x.scan=function(e){if(e||!this.didScan){for(var n in this.bindings)delete this.bindings[n];t(this.path,this.bindings),this.didScan=!0}},x.getBindings=function(){return this.scan(),this.bindings},x.lookup=function(e){for(var n=this;n&&!n.declares(e);n=n.parent);return n},x.getGlobalScope=function(){for(var e=this;!e.isGlobal;)e=e.parent;return e},n.exports=l},{"./node-path":128,"./types":133,assert:136}],132:[function(e,n,l){var t=e("../lib/types"),r=t.Type,a=t.builtInTypes,o=a.number;l.geq=function(e){return new r(function(n){return o.check(n)&&n>=e},o+" >= "+e)},l.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return!1},"true":function(){return!0},undefined:function(){}};var u=r.or(a.string,a.number,a.boolean,a.null,a.undefined);l.isPrimitive=new r(function(e){if(null===e)return!0;var n=typeof e;return!("object"===n||"function"===n)},u.toString())},{"../lib/types":133}],133:[function(e,n,l){function t(e,n){var l=this;g.ok(l instanceof t,l),g.strictEqual(b.call(e),_,e+" is not a function");var r=b.call(n);g.ok(r===_||r===v,n+" is neither a function nor a string"),Object.defineProperties(l,{name:{value:n},check:{value:function(n,t){var r=e.call(l,n,t);return!r&&t&&b.call(t)===_&&t(l,n),r}}})}function r(e){return C.check(e)?"{"+Object.keys(e).map(function(n){return n+": "+e[n]}).join(", ")+"}":S.check(e)?"["+e.map(r).join(", ")+"]":JSON.stringify(e)}function a(e,n){var l=b.call(e);return Object.defineProperty(k,n,{enumerable:!0,value:new t(function(e){return b.call(e)===l},n)}),k[n]}function o(e,n){return e instanceof t?e:e instanceof s?e.type:S.check(e)?t.fromArray(e):C.check(e)?t.fromObject(e):R.check(e)?new t(e,n):new t(function(n){return n===e},j.check(n)?function(){return e+""}:n)}function u(e,n,l,t){var r=this;g.ok(r instanceof u),w.assert(e),n=o(n);var a={name:{value:e},type:{value:n},hidden:{value:!!t}};R.check(l)&&(a.defaultFn={value:l}),Object.defineProperties(r,a)}function s(e){var n=this;g.ok(n instanceof s),Object.defineProperties(n,{typeName:{value:e},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new t(function(e,l){return n.check(e,l)},e)}})}function i(e){return e.replace(/^[A-Z]+/,function(e){var n=e.length;switch(n){case 0:return"";case 1:return e.toLowerCase();default:return e.slice(0,n-1).toLowerCase()+e.charAt(n-1)}})}function c(e){var n=s.fromValue(e);return n?n.fieldNames.slice(0):("type"in e&&g.ok(!1,"did not recognize object of type "+JSON.stringify(e.type)),Object.keys(e))}function d(e,n){var l=s.fromValue(e);if(l){var t=l.allFields[n];if(t)return t.getValue(e)}return e[n]}function p(e,n){n.length=0,n.push(e);for(var l=Object.create(null),t=0;t<n.length;++t){e=n[t];var r=L[e];g.strictEqual(r.finalized,!0),I.call(l,e)&&delete n[l[e]],l[e]=t,n.push.apply(n,r.baseNames)}for(var a=0,o=a,u=n.length;u>o;++o)I.call(n,o)&&(n[a++]=n[o]);n.length=a}function f(e,n){return Object.keys(n).forEach(function(l){e[l]=n[l]}),e}var g=e("assert"),h=Array.prototype,m=h.slice,y=(h.map,h.forEach),x=Object.prototype,b=x.toString,_=b.call(function(){}),v=b.call(""),I=x.hasOwnProperty,E=t.prototype;l.Type=t,E.assert=function(e,n){if(!this.check(e,n)){var l=r(e);return g.ok(!1,l+" does not match type "+this),!1}return!0},E.toString=function(){var e=this.name;return w.check(e)?e:R.check(e)?e.call(this)+"":e+" type"};var k={};l.builtInTypes=k;var w=a("","string"),R=a(function(){},"function"),S=a([],"array"),C=a({},"object"),A=(a(/./,"RegExp"),a(new Date,"Date"),a(3,"number")),j=(a(!0,"boolean"),a(null,"null"),a(void 0,"undefined"));t.or=function(){for(var e=[],n=arguments.length,l=0;n>l;++l)e.push(o(arguments[l]));return new t(function(l,t){for(var r=0;n>r;++r)if(e[r].check(l,t))return!0;return!1},function(){return e.join(" | ")})},t.fromArray=function(e){return g.ok(S.check(e)),g.strictEqual(e.length,1,"only one element type is permitted for typed arrays"),o(e[0]).arrayOf()},E.arrayOf=function(){var e=this;return new t(function(n,l){return S.check(n)&&n.every(function(n){return e.check(n,l)})},function(){return"["+e+"]"})},t.fromObject=function(e){var n=Object.keys(e).map(function(n){return new u(n,e[n])});return new t(function(e,l){return C.check(e)&&n.every(function(n){return n.type.check(e[n.name],l)})},function(){return"{ "+n.join(", ")+" }"})};var T=u.prototype;T.toString=function(){return JSON.stringify(this.name)+": "+this.type},T.getValue=function(e){var n=e[this.name];return j.check(n)?(this.defaultFn&&(n=this.defaultFn.call(e)),n):n},t.def=function(e){return w.assert(e),I.call(L,e)?L[e]:L[e]=new s(e)};var L=Object.create(null);s.fromValue=function(e){if(e&&"object"==typeof e){var n=e.type;if("string"==typeof n&&I.call(L,n)){var l=L[n];if(l.finalized)return l}}return null};var P=s.prototype;P.isSupertypeOf=function(e){return e instanceof s?(g.strictEqual(this.finalized,!0),g.strictEqual(e.finalized,!0),I.call(e.allSupertypes,this.typeName)):void g.ok(!1,e+" is not a Def")},l.getSupertypeNames=function(e){g.ok(I.call(L,e));var n=L[e];return g.strictEqual(n.finalized,!0),n.supertypeList.slice(1)},l.computeSupertypeLookupTable=function(e){for(var n={},l=Object.keys(L),t=l.length,r=0;t>r;++r){var a=l[r],o=L[a];
g.strictEqual(o.finalized,!0);for(var u=0;u<o.supertypeList.length;++u){var s=o.supertypeList[u];if(I.call(e,s)){n[a]=s;break}}}return n},P.checkAllFields=function(e,n){function l(l){var r=t[l],a=r.type,o=r.getValue(e);return a.check(o,n)}var t=this.allFields;return g.strictEqual(this.finalized,!0),C.check(e)&&Object.keys(t).every(l)},P.check=function(e,n){if(g.strictEqual(this.finalized,!0,"prematurely checking unfinalized type "+this.typeName),!C.check(e))return!1;var l=s.fromValue(e);return l?n&&l===this?this.checkAllFields(e,n):this.isSupertypeOf(l)?n?l.checkAllFields(e,n)&&this.checkAllFields(e,!1):!0:!1:"SourceLocation"===this.typeName||"Position"===this.typeName?this.checkAllFields(e,n):!1},P.bases=function(){var e=this.baseNames;return g.strictEqual(this.finalized,!1),y.call(arguments,function(n){w.assert(n),e.indexOf(n)<0&&e.push(n)}),this},Object.defineProperty(P,"buildable",{value:!1});var O={};l.builders=O;var M={};l.defineMethod=function(e,n){var l=M[e];return j.check(n)?delete M[e]:(R.assert(n),Object.defineProperty(M,e,{enumerable:!0,configurable:!0,value:n})),l},P.build=function(){var e=this;return Object.defineProperty(e,"buildParams",{value:m.call(arguments),writable:!1,enumerable:!1,configurable:!0}),g.strictEqual(e.finalized,!1),w.arrayOf().assert(e.buildParams),e.buildable?e:(e.field("type",e.typeName,function(){return e.typeName}),Object.defineProperty(e,"buildable",{value:!0}),Object.defineProperty(O,i(e.typeName),{enumerable:!0,value:function(){function n(n,o){if(!I.call(a,n)){var u=e.allFields;g.ok(I.call(u,n),n);var s,i=u[n],c=i.type;if(A.check(o)&&t>o)s=l[o];else if(i.defaultFn)s=i.defaultFn.call(a);else{var d="no value or default function given for field "+JSON.stringify(n)+" of "+e.typeName+"("+e.buildParams.map(function(e){return u[e]}).join(", ")+")";g.ok(!1,d)}c.check(s)||g.ok(!1,r(s)+" does not match field "+i+" of type "+e.typeName),a[n]=s}}var l=arguments,t=l.length,a=Object.create(M);return g.ok(e.finalized,"attempting to instantiate unfinalized type "+e.typeName),e.buildParams.forEach(function(e,l){n(e,l)}),Object.keys(e.allFields).forEach(function(e){n(e)}),g.strictEqual(a.type,e.typeName),a}}),e)},P.field=function(e,n,l,t){return g.strictEqual(this.finalized,!1),this.ownFields[e]=new u(e,n,l,t),this};var D={};l.namedTypes=D,l.getFieldNames=c,l.getFieldValue=d,l.eachField=function(e,n,l){c(e).forEach(function(l){n.call(this,l,d(e,l))},l)},l.someField=function(e,n,l){return c(e).some(function(l){return n.call(this,l,d(e,l))},l)},Object.defineProperty(P,"finalized",{value:!1}),P.finalize=function(){if(!this.finalized){var e=this.allFields,n=this.allSupertypes;this.baseNames.forEach(function(l){var t=L[l];t.finalize(),f(e,t.allFields),f(n,t.allSupertypes)}),f(e,this.ownFields),n[this.typeName]=this,this.fieldNames.length=0;for(var l in e)I.call(e,l)&&!e[l].hidden&&this.fieldNames.push(l);Object.defineProperty(D,this.typeName,{enumerable:!0,value:this.type}),Object.defineProperty(this,"finalized",{value:!0}),p(this.typeName,this.supertypeList)}},l.finalize=function(){Object.keys(L).forEach(function(e){L[e].finalize()})}},{assert:136}],134:[function(e,n,l){var t=e("./lib/types");e("./def/core"),e("./def/es6"),e("./def/es7"),e("./def/mozilla"),e("./def/e4x"),e("./def/fb-harmony"),t.finalize(),l.Type=t.Type,l.builtInTypes=t.builtInTypes,l.namedTypes=t.namedTypes,l.builders=t.builders,l.defineMethod=t.defineMethod,l.getFieldNames=t.getFieldNames,l.getFieldValue=t.getFieldValue,l.eachField=t.eachField,l.someField=t.someField,l.getSupertypeNames=t.getSupertypeNames,l.astNodesAreEquivalent=e("./lib/equiv"),l.finalize=t.finalize,l.NodePath=e("./lib/node-path"),l.PathVisitor=e("./lib/path-visitor"),l.visit=l.PathVisitor.visit},{"./def/core":121,"./def/e4x":122,"./def/es6":123,"./def/es7":124,"./def/fb-harmony":125,"./def/mozilla":126,"./lib/equiv":127,"./lib/node-path":128,"./lib/path-visitor":129,"./lib/types":133}],135:[function(){},{}],136:[function(e,n){function l(e,n){return p.isUndefined(n)?""+n:p.isNumber(n)&&!isFinite(n)?n.toString():p.isFunction(n)||p.isRegExp(n)?n.toString():n}function t(e,n){return p.isString(e)?e.length<n?e:e.slice(0,n):e}function r(e){return t(JSON.stringify(e.actual,l),128)+" "+e.operator+" "+t(JSON.stringify(e.expected,l),128)}function a(e,n,l,t,r){throw new h.AssertionError({message:l,actual:e,expected:n,operator:t,stackStartFunction:r})}function o(e,n){e||a(e,!0,n,"==",h.ok)}function u(e,n){if(e===n)return!0;if(p.isBuffer(e)&&p.isBuffer(n)){if(e.length!=n.length)return!1;for(var l=0;l<e.length;l++)if(e[l]!==n[l])return!1;return!0}return p.isDate(e)&&p.isDate(n)?e.getTime()===n.getTime():p.isRegExp(e)&&p.isRegExp(n)?e.source===n.source&&e.global===n.global&&e.multiline===n.multiline&&e.lastIndex===n.lastIndex&&e.ignoreCase===n.ignoreCase:p.isObject(e)||p.isObject(n)?i(e,n):e==n}function s(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function i(e,n){if(p.isNullOrUndefined(e)||p.isNullOrUndefined(n))return!1;if(e.prototype!==n.prototype)return!1;if(p.isPrimitive(e)||p.isPrimitive(n))return e===n;var l=s(e),t=s(n);if(l&&!t||!l&&t)return!1;if(l)return e=f.call(e),n=f.call(n),u(e,n);var r,a,o=m(e),i=m(n);if(o.length!=i.length)return!1;for(o.sort(),i.sort(),a=o.length-1;a>=0;a--)if(o[a]!=i[a])return!1;for(a=o.length-1;a>=0;a--)if(r=o[a],!u(e[r],n[r]))return!1;return!0}function c(e,n){return e&&n?"[object RegExp]"==Object.prototype.toString.call(n)?n.test(e):e instanceof n?!0:n.call({},e)===!0?!0:!1:!1}function d(e,n,l,t){var r;p.isString(l)&&(t=l,l=null);try{n()}catch(o){r=o}if(t=(l&&l.name?" ("+l.name+").":".")+(t?" "+t:"."),e&&!r&&a(r,l,"Missing expected exception"+t),!e&&c(r,l)&&a(r,l,"Got unwanted exception"+t),e&&r&&l&&!c(r,l)||!e&&r)throw r}var p=e("util/"),f=Array.prototype.slice,g=Object.prototype.hasOwnProperty,h=n.exports=o;h.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=r(this),this.generatedMessage=!0);var n=e.stackStartFunction||a;if(Error.captureStackTrace)Error.captureStackTrace(this,n);else{var l=new Error;if(l.stack){var t=l.stack,o=n.name,u=t.indexOf("\n"+o);if(u>=0){var s=t.indexOf("\n",u+1);t=t.substring(s+1)}this.stack=t}}},p.inherits(h.AssertionError,Error),h.fail=a,h.ok=o,h.equal=function(e,n,l){e!=n&&a(e,n,l,"==",h.equal)},h.notEqual=function(e,n,l){e==n&&a(e,n,l,"!=",h.notEqual)},h.deepEqual=function(e,n,l){u(e,n)||a(e,n,l,"deepEqual",h.deepEqual)},h.notDeepEqual=function(e,n,l){u(e,n)&&a(e,n,l,"notDeepEqual",h.notDeepEqual)},h.strictEqual=function(e,n,l){e!==n&&a(e,n,l,"===",h.strictEqual)},h.notStrictEqual=function(e,n,l){e===n&&a(e,n,l,"!==",h.notStrictEqual)},h.throws=function(){d.apply(this,[!0].concat(f.call(arguments)))},h.doesNotThrow=function(){d.apply(this,[!1].concat(f.call(arguments)))},h.ifError=function(e){if(e)throw e};var m=Object.keys||function(e){var n=[];for(var l in e)g.call(e,l)&&n.push(l);return n}},{"util/":161}],137:[function(e,n,l){function t(e,n,l){if(!(this instanceof t))return new t(e,n,l);var r,a=typeof e;if("number"===a)r=+e;else if("string"===a)r=t.byteLength(e,n);else{if("object"!==a||null===e)throw new TypeError("must start with number, buffer, array or string");"Buffer"===e.type&&D(e.data)&&(e=e.data),r=+e.length}if(r>N)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+N.toString(16)+" bytes");0>r?r=0:r>>>=0;var o=this;t.TYPED_ARRAY_SUPPORT?o=t._augment(new Uint8Array(r)):(o.length=r,o._isBuffer=!0);var u;if(t.TYPED_ARRAY_SUPPORT&&"number"==typeof e.byteLength)o._set(e);else if(R(e))if(t.isBuffer(e))for(u=0;r>u;u++)o[u]=e.readUInt8(u);else for(u=0;r>u;u++)o[u]=(e[u]%256+256)%256;else if("string"===a)o.write(e,0,n);else if("number"===a&&!t.TYPED_ARRAY_SUPPORT&&!l)for(u=0;r>u;u++)o[u]=0;return r>0&&r<=t.poolSize&&(o.parent=B),o}function r(e,n,l){if(!(this instanceof r))return new r(e,n,l);var a=new t(e,n,l);return delete a.parent,a}function a(e,n,l,t){l=Number(l)||0;var r=e.length-l;t?(t=Number(t),t>r&&(t=r)):t=r;var a=n.length;if(a%2!==0)throw new Error("Invalid hex string");t>a/2&&(t=a/2);for(var o=0;t>o;o++){var u=parseInt(n.substr(2*o,2),16);if(isNaN(u))throw new Error("Invalid hex string");e[l+o]=u}return o}function o(e,n,l,t){var r=L(C(n,e.length-l),e,l,t);return r}function u(e,n,l,t){var r=L(A(n),e,l,t);return r}function s(e,n,l,t){return u(e,n,l,t)}function i(e,n,l,t){var r=L(T(n),e,l,t);return r}function c(e,n,l,t){var r=L(j(n,e.length-l),e,l,t,2);return r}function d(e,n,l){return O.fromByteArray(0===n&&l===e.length?e:e.slice(n,l))}function p(e,n,l){var t="",r="";l=Math.min(e.length,l);for(var a=n;l>a;a++)e[a]<=127?(t+=P(r)+String.fromCharCode(e[a]),r=""):r+="%"+e[a].toString(16);return t+P(r)}function f(e,n,l){var t="";l=Math.min(e.length,l);for(var r=n;l>r;r++)t+=String.fromCharCode(127&e[r]);return t}function g(e,n,l){var t="";l=Math.min(e.length,l);for(var r=n;l>r;r++)t+=String.fromCharCode(e[r]);return t}function h(e,n,l){var t=e.length;(!n||0>n)&&(n=0),(!l||0>l||l>t)&&(l=t);for(var r="",a=n;l>a;a++)r+=S(e[a]);return r}function m(e,n,l){for(var t=e.slice(n,l),r="",a=0;a<t.length;a+=2)r+=String.fromCharCode(t[a]+256*t[a+1]);return r}function y(e,n,l){if(e%1!==0||0>e)throw new RangeError("offset is not uint");if(e+n>l)throw new RangeError("Trying to access beyond buffer length")}function x(e,n,l,r,a,o){if(!t.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(n>a||o>n)throw new RangeError("value is out of bounds");if(l+r>e.length)throw new RangeError("index out of range")}function b(e,n,l,t){0>n&&(n=65535+n+1);for(var r=0,a=Math.min(e.length-l,2);a>r;r++)e[l+r]=(n&255<<8*(t?r:1-r))>>>8*(t?r:1-r)}function _(e,n,l,t){0>n&&(n=4294967295+n+1);for(var r=0,a=Math.min(e.length-l,4);a>r;r++)e[l+r]=n>>>8*(t?r:3-r)&255}function v(e,n,l,t,r,a){if(n>r||a>n)throw new RangeError("value is out of bounds");if(l+t>e.length)throw new RangeError("index out of range");if(0>l)throw new RangeError("index out of range")}function I(e,n,l,t,r){return r||v(e,n,l,4,3.4028234663852886e38,-3.4028234663852886e38),M.write(e,n,l,t,23,4),l+4}function E(e,n,l,t,r){return r||v(e,n,l,8,1.7976931348623157e308,-1.7976931348623157e308),M.write(e,n,l,t,52,8),l+8}function k(e){if(e=w(e).replace(V,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function w(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function R(e){return D(e)||t.isBuffer(e)||e&&"object"==typeof e&&"number"==typeof e.length}function S(e){return 16>e?"0"+e.toString(16):e.toString(16)}function C(e,n){n=n||1/0;for(var l,t=e.length,r=null,a=[],o=0;t>o;o++){if(l=e.charCodeAt(o),l>55295&&57344>l){if(!r){if(l>56319){(n-=3)>-1&&a.push(239,191,189);continue}if(o+1===t){(n-=3)>-1&&a.push(239,191,189);continue}r=l;continue}if(56320>l){(n-=3)>-1&&a.push(239,191,189),r=l;continue}l=r-55296<<10|l-56320|65536,r=null}else r&&((n-=3)>-1&&a.push(239,191,189),r=null);if(128>l){if((n-=1)<0)break;a.push(l)}else if(2048>l){if((n-=2)<0)break;a.push(l>>6|192,63&l|128)}else if(65536>l){if((n-=3)<0)break;a.push(l>>12|224,l>>6&63|128,63&l|128)}else{if(!(2097152>l))throw new Error("Invalid code point");if((n-=4)<0)break;a.push(l>>18|240,l>>12&63|128,l>>6&63|128,63&l|128)}}return a}function A(e){for(var n=[],l=0;l<e.length;l++)n.push(255&e.charCodeAt(l));return n}function j(e,n){for(var l,t,r,a=[],o=0;o<e.length&&!((n-=2)<0);o++)l=e.charCodeAt(o),t=l>>8,r=l%256,a.push(r),a.push(t);return a}function T(e){return O.toByteArray(k(e))}function L(e,n,l,t,r){r&&(t-=t%r);for(var a=0;t>a&&!(a+l>=n.length||a>=e.length);a++)n[a+l]=e[a];return a}function P(e){try{return decodeURIComponent(e)}catch(n){return String.fromCharCode(65533)}}var O=e("base64-js"),M=e("ieee754"),D=e("is-array");l.Buffer=t,l.SlowBuffer=r,l.INSPECT_MAX_BYTES=50,t.poolSize=8192;var N=1073741823,B={};t.TYPED_ARRAY_SUPPORT=function(){try{var e=new ArrayBuffer(0),n=new Uint8Array(e);return n.foo=function(){return 42},42===n.foo()&&"function"==typeof n.subarray&&0===new Uint8Array(1).subarray(1,1).byteLength}catch(l){return!1}}(),t.isBuffer=function(e){return!(null==e||!e._isBuffer)},t.compare=function(e,n){if(!t.isBuffer(e)||!t.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(e===n)return 0;for(var l=e.length,r=n.length,a=0,o=Math.min(l,r);o>a&&e[a]===n[a];a++);return a!==o&&(l=e[a],r=n[a]),r>l?-1:l>r?1:0},t.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},t.concat=function(e,n){if(!D(e))throw new TypeError("Usage: Buffer.concat(list[, length])");if(0===e.length)return new t(0);if(1===e.length)return e[0];var l;if(void 0===n)for(n=0,l=0;l<e.length;l++)n+=e[l].length;var r=new t(n),a=0;for(l=0;l<e.length;l++){var o=e[l];o.copy(r,a),a+=o.length}return r},t.byteLength=function(e,n){var l;switch(e+="",n||"utf8"){case"ascii":case"binary":case"raw":l=e.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":l=2*e.length;break;case"hex":l=e.length>>>1;break;case"utf8":case"utf-8":l=C(e).length;break;case"base64":l=T(e).length;break;default:l=e.length}return l},t.prototype.length=void 0,t.prototype.parent=void 0,t.prototype.toString=function(e,n,l){var t=!1;if(n>>>=0,l=void 0===l||1/0===l?this.length:l>>>0,e||(e="utf8"),0>n&&(n=0),l>this.length&&(l=this.length),n>=l)return"";for(;;)switch(e){case"hex":return h(this,n,l);case"utf8":case"utf-8":return p(this,n,l);case"ascii":return f(this,n,l);case"binary":return g(this,n,l);case"base64":return d(this,n,l);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m(this,n,l);default:if(t)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),t=!0}},t.prototype.equals=function(e){if(!t.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:0===t.compare(this,e)},t.prototype.inspect=function(){var e="",n=l.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),"<Buffer "+e+">"},t.prototype.compare=function(e){if(!t.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?0:t.compare(this,e)},t.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},t.prototype.set=function(e,n){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,n)},t.prototype.write=function(e,n,l,t){if(isFinite(n))isFinite(l)||(t=l,l=void 0);else{var r=t;t=n,n=l,l=r}if(n=Number(n)||0,0>l||0>n||n>this.length)throw new RangeError("attempt to write outside buffer bounds");var d=this.length-n;l?(l=Number(l),l>d&&(l=d)):l=d,t=String(t||"utf8").toLowerCase();var p;switch(t){case"hex":p=a(this,e,n,l);break;case"utf8":case"utf-8":p=o(this,e,n,l);break;case"ascii":p=u(this,e,n,l);break;case"binary":p=s(this,e,n,l);break;case"base64":p=i(this,e,n,l);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":p=c(this,e,n,l);break;default:throw new TypeError("Unknown encoding: "+t)}return p},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},t.prototype.slice=function(e,n){var l=this.length;e=~~e,n=void 0===n?l:~~n,0>e?(e+=l,0>e&&(e=0)):e>l&&(e=l),0>n?(n+=l,0>n&&(n=0)):n>l&&(n=l),e>n&&(n=e);var r;if(t.TYPED_ARRAY_SUPPORT)r=t._augment(this.subarray(e,n));else{var a=n-e;r=new t(a,void 0,!0);for(var o=0;a>o;o++)r[o]=this[o+e]}return r.length&&(r.parent=this.parent||this),r},t.prototype.readUIntLE=function(e,n,l){e>>>=0,n>>>=0,l||y(e,n,this.length);for(var t=this[e],r=1,a=0;++a<n&&(r*=256);)t+=this[e+a]*r;return t},t.prototype.readUIntBE=function(e,n,l){e>>>=0,n>>>=0,l||y(e,n,this.length);for(var t=this[e+--n],r=1;n>0&&(r*=256);)t+=this[e+--n]*r;return t},t.prototype.readUInt8=function(e,n){return n||y(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,n){return n||y(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,n){return n||y(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,n){return n||y(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,n){return n||y(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,n,l){e>>>=0,n>>>=0,l||y(e,n,this.length);for(var t=this[e],r=1,a=0;++a<n&&(r*=256);)t+=this[e+a]*r;return r*=128,t>=r&&(t-=Math.pow(2,8*n)),t},t.prototype.readIntBE=function(e,n,l){e>>>=0,n>>>=0,l||y(e,n,this.length);for(var t=n,r=1,a=this[e+--t];t>0&&(r*=256);)a+=this[e+--t]*r;return r*=128,a>=r&&(a-=Math.pow(2,8*n)),a},t.prototype.readInt8=function(e,n){return n||y(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,n){n||y(e,2,this.length);var l=this[e]|this[e+1]<<8;return 32768&l?4294901760|l:l},t.prototype.readInt16BE=function(e,n){n||y(e,2,this.length);var l=this[e+1]|this[e]<<8;return 32768&l?4294901760|l:l},t.prototype.readInt32LE=function(e,n){return n||y(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,n){return n||y(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,n){return n||y(e,4,this.length),M.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,n){return n||y(e,4,this.length),M.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,n){return n||y(e,8,this.length),M.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,n){return n||y(e,8,this.length),M.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,n,l,t){e=+e,n>>>=0,l>>>=0,t||x(this,e,n,l,Math.pow(2,8*l),0);var r=1,a=0;for(this[n]=255&e;++a<l&&(r*=256);)this[n+a]=e/r>>>0&255;return n+l},t.prototype.writeUIntBE=function(e,n,l,t){e=+e,n>>>=0,l>>>=0,t||x(this,e,n,l,Math.pow(2,8*l),0);var r=l-1,a=1;for(this[n+r]=255&e;--r>=0&&(a*=256);)this[n+r]=e/a>>>0&255;return n+l},t.prototype.writeUInt8=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,1,255,0),t.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[n]=e,n+1},t.prototype.writeUInt16LE=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=e,this[n+1]=e>>>8):b(this,e,n,!0),n+2},t.prototype.writeUInt16BE=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=e>>>8,this[n+1]=e):b(this,e,n,!1),n+2},t.prototype.writeUInt32LE=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n+3]=e>>>24,this[n+2]=e>>>16,this[n+1]=e>>>8,this[n]=e):_(this,e,n,!0),n+4},t.prototype.writeUInt32BE=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n]=e>>>24,this[n+1]=e>>>16,this[n+2]=e>>>8,this[n+3]=e):_(this,e,n,!1),n+4},t.prototype.writeIntLE=function(e,n,l,t){e=+e,n>>>=0,t||x(this,e,n,l,Math.pow(2,8*l-1)-1,-Math.pow(2,8*l-1));var r=0,a=1,o=0>e?1:0;for(this[n]=255&e;++r<l&&(a*=256);)this[n+r]=(e/a>>0)-o&255;return n+l},t.prototype.writeIntBE=function(e,n,l,t){e=+e,n>>>=0,t||x(this,e,n,l,Math.pow(2,8*l-1)-1,-Math.pow(2,8*l-1));var r=l-1,a=1,o=0>e?1:0;for(this[n+r]=255&e;--r>=0&&(a*=256);)this[n+r]=(e/a>>0)-o&255;return n+l},t.prototype.writeInt8=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,1,127,-128),t.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),0>e&&(e=255+e+1),this[n]=e,n+1},t.prototype.writeInt16LE=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=e,this[n+1]=e>>>8):b(this,e,n,!0),n+2},t.prototype.writeInt16BE=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=e>>>8,this[n+1]=e):b(this,e,n,!1),n+2},t.prototype.writeInt32LE=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,4,2147483647,-2147483648),t.TYPED_ARRAY_SUPPORT?(this[n]=e,this[n+1]=e>>>8,this[n+2]=e>>>16,this[n+3]=e>>>24):_(this,e,n,!0),n+4},t.prototype.writeInt32BE=function(e,n,l){return e=+e,n>>>=0,l||x(this,e,n,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),t.TYPED_ARRAY_SUPPORT?(this[n]=e>>>24,this[n+1]=e>>>16,this[n+2]=e>>>8,this[n+3]=e):_(this,e,n,!1),n+4},t.prototype.writeFloatLE=function(e,n,l){return I(this,e,n,!0,l)},t.prototype.writeFloatBE=function(e,n,l){return I(this,e,n,!1,l)},t.prototype.writeDoubleLE=function(e,n,l){return E(this,e,n,!0,l)},t.prototype.writeDoubleBE=function(e,n,l){return E(this,e,n,!1,l)},t.prototype.copy=function(e,n,l,r){var a=this;if(l||(l=0),r||0===r||(r=this.length),n>=e.length&&(n=e.length),n||(n=0),r>0&&l>r&&(r=l),r===l)return 0;if(0===e.length||0===a.length)return 0;if(0>n)throw new RangeError("targetStart out of bounds");if(0>l||l>=a.length)throw new RangeError("sourceStart out of bounds");if(0>r)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-n<r-l&&(r=e.length-n+l);var o=r-l;if(1e3>o||!t.TYPED_ARRAY_SUPPORT)for(var u=0;o>u;u++)e[u+n]=this[u+l];else e._set(this.subarray(l,l+o),n);return o},t.prototype.fill=function(e,n,l){if(e||(e=0),n||(n=0),l||(l=this.length),n>l)throw new RangeError("end < start");if(l!==n&&0!==this.length){if(0>n||n>=this.length)throw new RangeError("start out of bounds");if(0>l||l>this.length)throw new RangeError("end out of bounds");var t;if("number"==typeof e)for(t=n;l>t;t++)this[t]=e;else{var r=C(e.toString()),a=r.length;for(t=n;l>t;t++)this[t]=r[t%a]}return this}},t.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(t.TYPED_ARRAY_SUPPORT)return new t(this).buffer;for(var e=new Uint8Array(this.length),n=0,l=e.length;l>n;n+=1)e[n]=this[n];return e.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser")};var F=t.prototype;t._augment=function(e){return e.constructor=t,e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=F.get,e.set=F.set,e.write=F.write,e.toString=F.toString,e.toLocaleString=F.toString,e.toJSON=F.toJSON,e.equals=F.equals,e.compare=F.compare,e.copy=F.copy,e.slice=F.slice,e.readUIntLE=F.readUIntLE,e.readUIntBE=F.readUIntBE,e.readUInt8=F.readUInt8,e.readUInt16LE=F.readUInt16LE,e.readUInt16BE=F.readUInt16BE,e.readUInt32LE=F.readUInt32LE,e.readUInt32BE=F.readUInt32BE,e.readIntLE=F.readIntLE,e.readIntBE=F.readIntBE,e.readInt8=F.readInt8,e.readInt16LE=F.readInt16LE,e.readInt16BE=F.readInt16BE,e.readInt32LE=F.readInt32LE,e.readInt32BE=F.readInt32BE,e.readFloatLE=F.readFloatLE,e.readFloatBE=F.readFloatBE,e.readDoubleLE=F.readDoubleLE,e.readDoubleBE=F.readDoubleBE,e.writeUInt8=F.writeUInt8,e.writeUIntLE=F.writeUIntLE,e.writeUIntBE=F.writeUIntBE,e.writeUInt16LE=F.writeUInt16LE,e.writeUInt16BE=F.writeUInt16BE,e.writeUInt32LE=F.writeUInt32LE,e.writeUInt32BE=F.writeUInt32BE,e.writeIntLE=F.writeIntLE,e.writeIntBE=F.writeIntBE,e.writeInt8=F.writeInt8,e.writeInt16LE=F.writeInt16LE,e.writeInt16BE=F.writeInt16BE,e.writeInt32LE=F.writeInt32LE,e.writeInt32BE=F.writeInt32BE,e.writeFloatLE=F.writeFloatLE,e.writeFloatBE=F.writeFloatBE,e.writeDoubleLE=F.writeDoubleLE,e.writeDoubleBE=F.writeDoubleBE,e.fill=F.fill,e.inspect=F.inspect,e.toArrayBuffer=F.toArrayBuffer,e};var V=/[^+\/0-9A-z\-]/g},{"base64-js":138,ieee754:139,"is-array":140}],138:[function(e,n,l){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(e){"use strict";function n(e){var n=e.charCodeAt(0);return n===o||n===d?62:n===u||n===p?63:s>n?-1:s+10>n?n-s+26+26:c+26>n?n-c:i+26>n?n-i+26:void 0}function l(e){function l(e){i[d++]=e}var t,r,o,u,s,i;if(e.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var c=e.length;s="="===e.charAt(c-2)?2:"="===e.charAt(c-1)?1:0,i=new a(3*e.length/4-s),o=s>0?e.length-4:e.length;var d=0;for(t=0,r=0;o>t;t+=4,r+=3)u=n(e.charAt(t))<<18|n(e.charAt(t+1))<<12|n(e.charAt(t+2))<<6|n(e.charAt(t+3)),l((16711680&u)>>16),l((65280&u)>>8),l(255&u);return 2===s?(u=n(e.charAt(t))<<2|n(e.charAt(t+1))>>4,l(255&u)):1===s&&(u=n(e.charAt(t))<<10|n(e.charAt(t+1))<<4|n(e.charAt(t+2))>>2,l(u>>8&255),l(255&u)),i}function r(e){function n(e){return t.charAt(e)}function l(e){return n(e>>18&63)+n(e>>12&63)+n(e>>6&63)+n(63&e)}var r,a,o,u=e.length%3,s="";for(r=0,o=e.length-u;o>r;r+=3)a=(e[r]<<16)+(e[r+1]<<8)+e[r+2],s+=l(a);switch(u){case 1:a=e[e.length-1],s+=n(a>>2),s+=n(a<<4&63),s+="==";break;case 2:a=(e[e.length-2]<<8)+e[e.length-1],s+=n(a>>10),s+=n(a>>4&63),s+=n(a<<2&63),s+="="}return s}var a="undefined"!=typeof Uint8Array?Uint8Array:Array,o="+".charCodeAt(0),u="/".charCodeAt(0),s="0".charCodeAt(0),i="a".charCodeAt(0),c="A".charCodeAt(0),d="-".charCodeAt(0),p="_".charCodeAt(0);e.toByteArray=l,e.fromByteArray=r}("undefined"==typeof l?this.base64js={}:l)},{}],139:[function(e,n,l){l.read=function(e,n,l,t,r){var a,o,u=8*r-t-1,s=(1<<u)-1,i=s>>1,c=-7,d=l?r-1:0,p=l?-1:1,f=e[n+d];for(d+=p,a=f&(1<<-c)-1,f>>=-c,c+=u;c>0;a=256*a+e[n+d],d+=p,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=t;c>0;o=256*o+e[n+d],d+=p,c-=8);if(0===a)a=1-i;else{if(a===s)return o?0/0:1/0*(f?-1:1);o+=Math.pow(2,t),a-=i}return(f?-1:1)*o*Math.pow(2,a-t)},l.write=function(e,n,l,t,r,a){var o,u,s,i=8*a-r-1,c=(1<<i)-1,d=c>>1,p=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=t?0:a-1,g=t?1:-1,h=0>n||0===n&&0>1/n?1:0;for(n=Math.abs(n),isNaN(n)||1/0===n?(u=isNaN(n)?1:0,o=c):(o=Math.floor(Math.log(n)/Math.LN2),n*(s=Math.pow(2,-o))<1&&(o--,s*=2),n+=o+d>=1?p/s:p*Math.pow(2,1-d),n*s>=2&&(o++,s/=2),o+d>=c?(u=0,o=c):o+d>=1?(u=(n*s-1)*Math.pow(2,r),o+=d):(u=n*Math.pow(2,d-1)*Math.pow(2,r),o=0));r>=8;e[l+f]=255&u,f+=g,u/=256,r-=8);for(o=o<<r|u,i+=r;i>0;e[l+f]=255&o,f+=g,o/=256,i-=8);e[l+f-g]|=128*h}},{}],140:[function(e,n){var l=Array.isArray,t=Object.prototype.toString;n.exports=l||function(e){return!!e&&"[object Array]"==t.call(e)}},{}],141:[function(e,n){function l(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function t(e){return"function"==typeof e}function r(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}n.exports=l,l.EventEmitter=l,l.prototype._events=void 0,l.prototype._maxListeners=void 0,l.defaultMaxListeners=10,l.prototype.setMaxListeners=function(e){if(!r(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},l.prototype.emit=function(e){var n,l,r,u,s,i;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(n=arguments[1],n instanceof Error)throw n;throw TypeError('Uncaught, unspecified "error" event.')}if(l=this._events[e],o(l))return!1;if(t(l))switch(arguments.length){case 1:l.call(this);break;case 2:l.call(this,arguments[1]);break;case 3:l.call(this,arguments[1],arguments[2]);break;default:for(r=arguments.length,u=new Array(r-1),s=1;r>s;s++)u[s-1]=arguments[s];l.apply(this,u)}else if(a(l)){for(r=arguments.length,u=new Array(r-1),s=1;r>s;s++)u[s-1]=arguments[s];for(i=l.slice(),r=i.length,s=0;r>s;s++)i[s].apply(this,u)}return!0},l.prototype.addListener=function(e,n){var r;if(!t(n))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,t(n.listener)?n.listener:n),this._events[e]?a(this._events[e])?this._events[e].push(n):this._events[e]=[this._events[e],n]:this._events[e]=n,a(this._events[e])&&!this._events[e].warned){var r;r=o(this._maxListeners)?l.defaultMaxListeners:this._maxListeners,r&&r>0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())}return this},l.prototype.on=l.prototype.addListener,l.prototype.once=function(e,n){function l(){this.removeListener(e,l),r||(r=!0,n.apply(this,arguments))}if(!t(n))throw TypeError("listener must be a function");var r=!1;return l.listener=n,this.on(e,l),this},l.prototype.removeListener=function(e,n){var l,r,o,u;if(!t(n))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(l=this._events[e],o=l.length,r=-1,l===n||t(l.listener)&&l.listener===n)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,n);else if(a(l)){for(u=o;u-->0;)if(l[u]===n||l[u].listener&&l[u].listener===n){r=u;break}if(0>r)return this;1===l.length?(l.length=0,delete this._events[e]):l.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,n)}return this},l.prototype.removeAllListeners=function(e){var n,l;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(n in this._events)"removeListener"!==n&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events={},this}if(l=this._events[e],t(l))this.removeListener(e,l);else for(;l.length;)this.removeListener(e,l[l.length-1]);return delete this._events[e],this},l.prototype.listeners=function(e){var n;return n=this._events&&this._events[e]?t(this._events[e])?[this._events[e]]:this._events[e].slice():[]},l.listenerCount=function(e,n){var l;return l=e._events&&e._events[n]?t(e._events[n])?1:e._events[n].length:0}},{}],142:[function(e,n){n.exports="function"==typeof Object.create?function(e,n){e.super_=n,e.prototype=Object.create(n.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,n){e.super_=n;var l=function(){};l.prototype=n.prototype,e.prototype=new l,e.prototype.constructor=e}},{}],143:[function(e,n){n.exports=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)}},{}],144:[function(e,n,l){(function(e){function n(e,n){for(var l=0,t=e.length-1;t>=0;t--){var r=e[t];"."===r?e.splice(t,1):".."===r?(e.splice(t,1),l++):l&&(e.splice(t,1),l--)}if(n)for(;l--;l)e.unshift("..");return e}function t(e,n){if(e.filter)return e.filter(n);for(var l=[],t=0;t<e.length;t++)n(e[t],t,e)&&l.push(e[t]);return l}var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,a=function(e){return r.exec(e).slice(1)};l.resolve=function(){for(var l="",r=!1,a=arguments.length-1;a>=-1&&!r;a--){var o=a>=0?arguments[a]:e.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(l=o+"/"+l,r="/"===o.charAt(0))}return l=n(t(l.split("/"),function(e){return!!e}),!r).join("/"),(r?"/":"")+l||"."},l.normalize=function(e){var r=l.isAbsolute(e),a="/"===o(e,-1);return e=n(t(e.split("/"),function(e){return!!e}),!r).join("/"),e||r||(e="."),e&&a&&(e+="/"),(r?"/":"")+e},l.isAbsolute=function(e){return"/"===e.charAt(0)},l.join=function(){var e=Array.prototype.slice.call(arguments,0);return l.normalize(t(e,function(e){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},l.relative=function(e,n){function t(e){for(var n=0;n<e.length&&""===e[n];n++);for(var l=e.length-1;l>=0&&""===e[l];l--);return n>l?[]:e.slice(n,l-n+1)}e=l.resolve(e).substr(1),n=l.resolve(n).substr(1);for(var r=t(e.split("/")),a=t(n.split("/")),o=Math.min(r.length,a.length),u=o,s=0;o>s;s++)if(r[s]!==a[s]){u=s;break}for(var i=[],s=u;s<r.length;s++)i.push("..");return i=i.concat(a.slice(u)),i.join("/")},l.sep="/",l.delimiter=":",l.dirname=function(e){var n=a(e),l=n[0],t=n[1];return l||t?(t&&(t=t.substr(0,t.length-1)),l+t):"."},l.basename=function(e,n){var l=a(e)[2];return n&&l.substr(-1*n.length)===n&&(l=l.substr(0,l.length-n.length)),l},l.extname=function(e){return a(e)[3]};var o="b"==="ab".substr(-1)?function(e,n,l){return e.substr(n,l)}:function(e,n,l){return 0>n&&(n=e.length+n),e.substr(n,l)}}).call(this,e("_process"))},{_process:145}],145:[function(e,n){function l(){if(!o){o=!0;for(var e,n=a.length;n;){e=a,a=[];for(var l=-1;++l<n;)e[l]();n=a.length}o=!1}}function t(){}var r=n.exports={},a=[],o=!1;r.nextTick=function(e){a.push(e),o||setTimeout(l,0)},r.title="browser",r.browser=!0,r.env={},r.argv=[],r.version="",r.on=t,r.addListener=t,r.once=t,r.off=t,r.removeListener=t,r.removeAllListeners=t,r.emit=t,r.binding=function(){throw new Error("process.binding is not supported")
},r.cwd=function(){return"/"},r.chdir=function(){throw new Error("process.chdir is not supported")},r.umask=function(){return 0}},{}],146:[function(e,n){n.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":147}],147:[function(e,n){(function(l){function t(e){return this instanceof t?(s.call(this,e),i.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",r)):new t(e)}function r(){this.allowHalfOpen||this._writableState.ended||l.nextTick(this.end.bind(this))}function a(e,n){for(var l=0,t=e.length;t>l;l++)n(e[l],l)}n.exports=t;var o=Object.keys||function(e){var n=[];for(var l in e)n.push(l);return n},u=e("core-util-is");u.inherits=e("inherits");var s=e("./_stream_readable"),i=e("./_stream_writable");u.inherits(t,s),a(o(i.prototype),function(e){t.prototype[e]||(t.prototype[e]=i.prototype[e])})}).call(this,e("_process"))},{"./_stream_readable":149,"./_stream_writable":151,_process:145,"core-util-is":152,inherits:142}],148:[function(e,n){function l(e){return this instanceof l?void t.call(this,e):new l(e)}n.exports=l;var t=e("./_stream_transform"),r=e("core-util-is");r.inherits=e("inherits"),r.inherits(l,t),l.prototype._transform=function(e,n,l){l(null,e)}},{"./_stream_transform":150,"core-util-is":152,inherits:142}],149:[function(e,n){(function(l){function t(n){n=n||{};var l=n.highWaterMark;this.highWaterMark=l||0===l?l:16384,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=!1,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.calledRead=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.objectMode=!!n.objectMode,this.defaultEncoding=n.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,n.encoding&&(C||(C=e("string_decoder/").StringDecoder),this.decoder=new C(n.encoding),this.encoding=n.encoding)}function r(e){return this instanceof r?(this._readableState=new t(e,this),this.readable=!0,void R.call(this)):new r(e)}function a(e,n,l,t,r){var a=i(n,l);if(a)e.emit("error",a);else if(null===l||void 0===l)n.reading=!1,n.ended||c(e,n);else if(n.objectMode||l&&l.length>0)if(n.ended&&!r){var u=new Error("stream.push() after EOF");e.emit("error",u)}else if(n.endEmitted&&r){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else!n.decoder||r||t||(l=n.decoder.write(l)),n.length+=n.objectMode?1:l.length,r?n.buffer.unshift(l):(n.reading=!1,n.buffer.push(l)),n.needReadable&&d(e),f(e,n);else r||(n.reading=!1);return o(n)}function o(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}function u(e){if(e>=A)e=A;else{e--;for(var n=1;32>n;n<<=1)e|=e>>n;e++}return e}function s(e,n){return 0===n.length&&n.ended?0:n.objectMode?0===e?0:1:null===e||isNaN(e)?n.flowing&&n.buffer.length?n.buffer[0].length:n.length:0>=e?0:(e>n.highWaterMark&&(n.highWaterMark=u(e)),e>n.length?n.ended?n.length:(n.needReadable=!0,0):e)}function i(e,n){var l=null;return k.isBuffer(n)||"string"==typeof n||null===n||void 0===n||e.objectMode||(l=new TypeError("Invalid non-string/buffer chunk")),l}function c(e,n){if(n.decoder&&!n.ended){var l=n.decoder.end();l&&l.length&&(n.buffer.push(l),n.length+=n.objectMode?1:l.length)}n.ended=!0,n.length>0?d(e):_(e)}function d(e){var n=e._readableState;n.needReadable=!1,n.emittedReadable||(n.emittedReadable=!0,n.sync?l.nextTick(function(){p(e)}):p(e))}function p(e){e.emit("readable")}function f(e,n){n.readingMore||(n.readingMore=!0,l.nextTick(function(){g(e,n)}))}function g(e,n){for(var l=n.length;!n.reading&&!n.flowing&&!n.ended&&n.length<n.highWaterMark&&(e.read(0),l!==n.length);)l=n.length;n.readingMore=!1}function h(e){return function(){var n=e._readableState;n.awaitDrain--,0===n.awaitDrain&&m(e)}}function m(e){function n(e){var n=e.write(l);!1===n&&t.awaitDrain++}var l,t=e._readableState;for(t.awaitDrain=0;t.pipesCount&&null!==(l=e.read());)if(1===t.pipesCount?n(t.pipes,0,null):v(t.pipes,n),e.emit("data",l),t.awaitDrain>0)return;return 0===t.pipesCount?(t.flowing=!1,void(w.listenerCount(e,"data")>0&&x(e))):void(t.ranOut=!0)}function y(){this._readableState.ranOut&&(this._readableState.ranOut=!1,m(this))}function x(e,n){var t=e._readableState;if(t.flowing)throw new Error("Cannot switch to old mode now.");var r=n||!1,a=!1;e.readable=!0,e.pipe=R.prototype.pipe,e.on=e.addListener=R.prototype.on,e.on("readable",function(){a=!0;for(var n;!r&&null!==(n=e.read());)e.emit("data",n);null===n&&(a=!1,e._readableState.needReadable=!0)}),e.pause=function(){r=!0,this.emit("pause")},e.resume=function(){r=!1,a?l.nextTick(function(){e.emit("readable")}):this.read(0),this.emit("resume")},e.emit("readable")}function b(e,n){var l,t=n.buffer,r=n.length,a=!!n.decoder,o=!!n.objectMode;if(0===t.length)return null;if(0===r)l=null;else if(o)l=t.shift();else if(!e||e>=r)l=a?t.join(""):k.concat(t,r),t.length=0;else if(e<t[0].length){var u=t[0];l=u.slice(0,e),t[0]=u.slice(e)}else if(e===t[0].length)l=t.shift();else{l=a?"":new k(e);for(var s=0,i=0,c=t.length;c>i&&e>s;i++){var u=t[0],d=Math.min(e-s,u.length);a?l+=u.slice(0,d):u.copy(l,s,0,d),d<u.length?t[0]=u.slice(d):t.shift(),s+=d}}return l}function _(e){var n=e._readableState;if(n.length>0)throw new Error("endReadable called on non-empty stream");!n.endEmitted&&n.calledRead&&(n.ended=!0,l.nextTick(function(){n.endEmitted||0!==n.length||(n.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function v(e,n){for(var l=0,t=e.length;t>l;l++)n(e[l],l)}function I(e,n){for(var l=0,t=e.length;t>l;l++)if(e[l]===n)return l;return-1}n.exports=r;var E=e("isarray"),k=e("buffer").Buffer;r.ReadableState=t;var w=e("events").EventEmitter;w.listenerCount||(w.listenerCount=function(e,n){return e.listeners(n).length});var R=e("stream"),S=e("core-util-is");S.inherits=e("inherits");var C;S.inherits(r,R),r.prototype.push=function(e,n){var l=this._readableState;return"string"!=typeof e||l.objectMode||(n=n||l.defaultEncoding,n!==l.encoding&&(e=new k(e,n),n="")),a(this,l,e,n,!1)},r.prototype.unshift=function(e){var n=this._readableState;return a(this,n,e,"",!0)},r.prototype.setEncoding=function(n){C||(C=e("string_decoder/").StringDecoder),this._readableState.decoder=new C(n),this._readableState.encoding=n};var A=8388608;r.prototype.read=function(e){var n=this._readableState;n.calledRead=!0;var l,t=e;if(("number"!=typeof e||e>0)&&(n.emittedReadable=!1),0===e&&n.needReadable&&(n.length>=n.highWaterMark||n.ended))return d(this),null;if(e=s(e,n),0===e&&n.ended)return l=null,n.length>0&&n.decoder&&(l=b(e,n),n.length-=l.length),0===n.length&&_(this),l;var r=n.needReadable;return n.length-e<=n.highWaterMark&&(r=!0),(n.ended||n.reading)&&(r=!1),r&&(n.reading=!0,n.sync=!0,0===n.length&&(n.needReadable=!0),this._read(n.highWaterMark),n.sync=!1),r&&!n.reading&&(e=s(t,n)),l=e>0?b(e,n):null,null===l&&(n.needReadable=!0,e=0),n.length-=e,0!==n.length||n.ended||(n.needReadable=!0),n.ended&&!n.endEmitted&&0===n.length&&_(this),l},r.prototype._read=function(){this.emit("error",new Error("not implemented"))},r.prototype.pipe=function(e,n){function t(e){e===c&&a()}function r(){e.end()}function a(){e.removeListener("close",u),e.removeListener("finish",s),e.removeListener("drain",g),e.removeListener("error",o),e.removeListener("unpipe",t),c.removeListener("end",r),c.removeListener("end",a),(!e._writableState||e._writableState.needDrain)&&g()}function o(n){i(),e.removeListener("error",o),0===w.listenerCount(e,"error")&&e.emit("error",n)}function u(){e.removeListener("finish",s),i()}function s(){e.removeListener("close",u),i()}function i(){c.unpipe(e)}var c=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=e;break;case 1:d.pipes=[d.pipes,e];break;default:d.pipes.push(e)}d.pipesCount+=1;var p=(!n||n.end!==!1)&&e!==l.stdout&&e!==l.stderr,f=p?r:a;d.endEmitted?l.nextTick(f):c.once("end",f),e.on("unpipe",t);var g=h(c);return e.on("drain",g),e._events&&e._events.error?E(e._events.error)?e._events.error.unshift(o):e._events.error=[o,e._events.error]:e.on("error",o),e.once("close",u),e.once("finish",s),e.emit("pipe",c),d.flowing||(this.on("readable",y),d.flowing=!0,l.nextTick(function(){m(c)})),e},r.prototype.unpipe=function(e){var n=this._readableState;if(0===n.pipesCount)return this;if(1===n.pipesCount)return e&&e!==n.pipes?this:(e||(e=n.pipes),n.pipes=null,n.pipesCount=0,this.removeListener("readable",y),n.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var l=n.pipes,t=n.pipesCount;n.pipes=null,n.pipesCount=0,this.removeListener("readable",y),n.flowing=!1;for(var r=0;t>r;r++)l[r].emit("unpipe",this);return this}var r=I(n.pipes,e);return-1===r?this:(n.pipes.splice(r,1),n.pipesCount-=1,1===n.pipesCount&&(n.pipes=n.pipes[0]),e.emit("unpipe",this),this)},r.prototype.on=function(e,n){var l=R.prototype.on.call(this,e,n);if("data"!==e||this._readableState.flowing||x(this),"readable"===e&&this.readable){var t=this._readableState;t.readableListening||(t.readableListening=!0,t.emittedReadable=!1,t.needReadable=!0,t.reading?t.length&&d(this,t):this.read(0))}return l},r.prototype.addListener=r.prototype.on,r.prototype.resume=function(){x(this),this.read(0),this.emit("resume")},r.prototype.pause=function(){x(this,!0),this.emit("pause")},r.prototype.wrap=function(e){var n=this._readableState,l=!1,t=this;e.on("end",function(){if(n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(r){if(n.decoder&&(r=n.decoder.write(r)),(!n.objectMode||null!==r&&void 0!==r)&&(n.objectMode||r&&r.length)){var a=t.push(r);a||(l=!0,e.pause())}});for(var r in e)"function"==typeof e[r]&&"undefined"==typeof this[r]&&(this[r]=function(n){return function(){return e[n].apply(e,arguments)}}(r));var a=["error","close","destroy","pause","resume"];return v(a,function(n){e.on(n,t.emit.bind(t,n))}),t._read=function(){l&&(l=!1,e.resume())},t},r._fromList=b}).call(this,e("_process"))},{_process:145,buffer:137,"core-util-is":152,events:141,inherits:142,isarray:143,stream:157,"string_decoder/":158}],150:[function(e,n){function l(e,n){this.afterTransform=function(e,l){return t(n,e,l)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null}function t(e,n,l){var t=e._transformState;t.transforming=!1;var r=t.writecb;if(!r)return e.emit("error",new Error("no writecb in Transform class"));t.writechunk=null,t.writecb=null,null!==l&&void 0!==l&&e.push(l),r&&r(n);var a=e._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&e._read(a.highWaterMark)}function r(e){if(!(this instanceof r))return new r(e);o.call(this,e);var n=(this._transformState=new l(e,this),this);this._readableState.needReadable=!0,this._readableState.sync=!1,this.once("finish",function(){"function"==typeof this._flush?this._flush(function(e){a(n,e)}):a(n)})}function a(e,n){if(n)return e.emit("error",n);var l=e._writableState,t=(e._readableState,e._transformState);if(l.length)throw new Error("calling transform done when ws.length != 0");if(t.transforming)throw new Error("calling transform done when still transforming");return e.push(null)}n.exports=r;var o=e("./_stream_duplex"),u=e("core-util-is");u.inherits=e("inherits"),u.inherits(r,o),r.prototype.push=function(e,n){return this._transformState.needTransform=!1,o.prototype.push.call(this,e,n)},r.prototype._transform=function(){throw new Error("not implemented")},r.prototype._write=function(e,n,l){var t=this._transformState;if(t.writecb=l,t.writechunk=e,t.writeencoding=n,!t.transforming){var r=this._readableState;(t.needTransform||r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}},r.prototype._read=function(){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0}},{"./_stream_duplex":147,"core-util-is":152,inherits:142}],151:[function(e,n){(function(l){function t(e,n,l){this.chunk=e,this.encoding=n,this.callback=l}function r(e,n){e=e||{};var l=e.highWaterMark;this.highWaterMark=l||0===l?l:16384,this.objectMode=!!e.objectMode,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var t=e.decodeStrings===!1;this.decodeStrings=!t,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){f(n,e)},this.writecb=null,this.writelen=0,this.buffer=[],this.errorEmitted=!1}function a(n){var l=e("./_stream_duplex");return this instanceof a||this instanceof l?(this._writableState=new r(n,this),this.writable=!0,void I.call(this)):new a(n)}function o(e,n,t){var r=new Error("write after end");e.emit("error",r),l.nextTick(function(){t(r)})}function u(e,n,t,r){var a=!0;if(!_.isBuffer(t)&&"string"!=typeof t&&null!==t&&void 0!==t&&!n.objectMode){var o=new TypeError("Invalid non-string/buffer chunk");e.emit("error",o),l.nextTick(function(){r(o)}),a=!1}return a}function s(e,n,l){return e.objectMode||e.decodeStrings===!1||"string"!=typeof n||(n=new _(n,l)),n}function i(e,n,l,r,a){l=s(n,l,r),_.isBuffer(l)&&(r="buffer");var o=n.objectMode?1:l.length;n.length+=o;var u=n.length<n.highWaterMark;return u||(n.needDrain=!0),n.writing?n.buffer.push(new t(l,r,a)):c(e,n,o,l,r,a),u}function c(e,n,l,t,r,a){n.writelen=l,n.writecb=a,n.writing=!0,n.sync=!0,e._write(t,r,n.onwrite),n.sync=!1}function d(e,n,t,r,a){t?l.nextTick(function(){a(r)}):a(r),e._writableState.errorEmitted=!0,e.emit("error",r)}function p(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function f(e,n){var t=e._writableState,r=t.sync,a=t.writecb;if(p(t),n)d(e,t,r,n,a);else{var o=y(e,t);o||t.bufferProcessing||!t.buffer.length||m(e,t),r?l.nextTick(function(){g(e,t,o,a)}):g(e,t,o,a)}}function g(e,n,l,t){l||h(e,n),t(),l&&x(e,n)}function h(e,n){0===n.length&&n.needDrain&&(n.needDrain=!1,e.emit("drain"))}function m(e,n){n.bufferProcessing=!0;for(var l=0;l<n.buffer.length;l++){var t=n.buffer[l],r=t.chunk,a=t.encoding,o=t.callback,u=n.objectMode?1:r.length;if(c(e,n,u,r,a,o),n.writing){l++;break}}n.bufferProcessing=!1,l<n.buffer.length?n.buffer=n.buffer.slice(l):n.buffer.length=0}function y(e,n){return n.ending&&0===n.length&&!n.finished&&!n.writing}function x(e,n){var l=y(e,n);return l&&(n.finished=!0,e.emit("finish")),l}function b(e,n,t){n.ending=!0,x(e,n),t&&(n.finished?l.nextTick(t):e.once("finish",t)),n.ended=!0}n.exports=a;var _=e("buffer").Buffer;a.WritableState=r;var v=e("core-util-is");v.inherits=e("inherits");var I=e("stream");v.inherits(a,I),a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},a.prototype.write=function(e,n,l){var t=this._writableState,r=!1;return"function"==typeof n&&(l=n,n=null),_.isBuffer(e)?n="buffer":n||(n=t.defaultEncoding),"function"!=typeof l&&(l=function(){}),t.ended?o(this,t,l):u(this,t,e,l)&&(r=i(this,t,e,n,l)),r},a.prototype._write=function(e,n,l){l(new Error("not implemented"))},a.prototype.end=function(e,n,l){var t=this._writableState;"function"==typeof e?(l=e,e=null,n=null):"function"==typeof n&&(l=n,n=null),"undefined"!=typeof e&&null!==e&&this.write(e,n),t.ending||t.finished||b(this,t,l)}}).call(this,e("_process"))},{"./_stream_duplex":147,_process:145,buffer:137,"core-util-is":152,inherits:142,stream:157}],152:[function(e,n,l){(function(e){function n(e){return Array.isArray(e)}function t(e){return"boolean"==typeof e}function r(e){return null===e}function a(e){return null==e}function o(e){return"number"==typeof e}function u(e){return"string"==typeof e}function s(e){return"symbol"==typeof e}function i(e){return void 0===e}function c(e){return d(e)&&"[object RegExp]"===y(e)}function d(e){return"object"==typeof e&&null!==e}function p(e){return d(e)&&"[object Date]"===y(e)}function f(e){return d(e)&&("[object Error]"===y(e)||e instanceof Error)}function g(e){return"function"==typeof e}function h(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function m(n){return e.isBuffer(n)}function y(e){return Object.prototype.toString.call(e)}l.isArray=n,l.isBoolean=t,l.isNull=r,l.isNullOrUndefined=a,l.isNumber=o,l.isString=u,l.isSymbol=s,l.isUndefined=i,l.isRegExp=c,l.isObject=d,l.isDate=p,l.isError=f,l.isFunction=g,l.isPrimitive=h,l.isBuffer=m}).call(this,e("buffer").Buffer)},{buffer:137}],153:[function(e,n){n.exports=e("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":148}],154:[function(e,n,l){var t=e("stream");l=n.exports=e("./lib/_stream_readable.js"),l.Stream=t,l.Readable=l,l.Writable=e("./lib/_stream_writable.js"),l.Duplex=e("./lib/_stream_duplex.js"),l.Transform=e("./lib/_stream_transform.js"),l.PassThrough=e("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":147,"./lib/_stream_passthrough.js":148,"./lib/_stream_readable.js":149,"./lib/_stream_transform.js":150,"./lib/_stream_writable.js":151,stream:157}],155:[function(e,n){n.exports=e("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":150}],156:[function(e,n){n.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":151}],157:[function(e,n){function l(){t.call(this)}n.exports=l;var t=e("events").EventEmitter,r=e("inherits");r(l,t),l.Readable=e("readable-stream/readable.js"),l.Writable=e("readable-stream/writable.js"),l.Duplex=e("readable-stream/duplex.js"),l.Transform=e("readable-stream/transform.js"),l.PassThrough=e("readable-stream/passthrough.js"),l.Stream=l,l.prototype.pipe=function(e,n){function l(n){e.writable&&!1===e.write(n)&&i.pause&&i.pause()}function r(){i.readable&&i.resume&&i.resume()}function a(){c||(c=!0,e.end())}function o(){c||(c=!0,"function"==typeof e.destroy&&e.destroy())}function u(e){if(s(),0===t.listenerCount(this,"error"))throw e}function s(){i.removeListener("data",l),e.removeListener("drain",r),i.removeListener("end",a),i.removeListener("close",o),i.removeListener("error",u),e.removeListener("error",u),i.removeListener("end",s),i.removeListener("close",s),e.removeListener("close",s)}var i=this;i.on("data",l),e.on("drain",r),e._isStdio||n&&n.end===!1||(i.on("end",a),i.on("close",o));var c=!1;return i.on("error",u),e.on("error",u),i.on("end",s),i.on("close",s),e.on("close",s),e.emit("pipe",i),e}},{events:141,inherits:142,"readable-stream/duplex.js":146,"readable-stream/passthrough.js":153,"readable-stream/readable.js":154,"readable-stream/transform.js":155,"readable-stream/writable.js":156}],158:[function(e,n,l){function t(e){if(e&&!s(e))throw new Error("Unknown encoding: "+e)}function r(e){return e.toString(this.encoding)}function a(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function o(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var u=e("buffer").Buffer,s=u.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},i=l.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),t(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=a;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=o;break;default:return void(this.write=r)}this.charBuffer=new u(6),this.charReceived=0,this.charLength=0};i.prototype.write=function(e){for(var n="";this.charLength;){var l=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,l),this.charReceived+=l,this.charReceived<this.charLength)return"";e=e.slice(l,e.length),n=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var t=n.charCodeAt(n.length-1);if(!(t>=55296&&56319>=t)){if(this.charReceived=this.charLength=0,0===e.length)return n;break}this.charLength+=this.surrogateSize,n=""}this.detectIncompleteChar(e);var r=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,r),r-=this.charReceived),n+=e.toString(this.encoding,0,r);var r=n.length-1,t=n.charCodeAt(r);if(t>=55296&&56319>=t){var a=this.surrogateSize;return this.charLength+=a,this.charReceived+=a,this.charBuffer.copy(this.charBuffer,a,0,a),e.copy(this.charBuffer,0,0,a),n.substring(0,r)}return n},i.prototype.detectIncompleteChar=function(e){for(var n=e.length>=3?3:e.length;n>0;n--){var l=e[e.length-n];if(1==n&&l>>5==6){this.charLength=2;break}if(2>=n&&l>>4==14){this.charLength=3;break}if(3>=n&&l>>3==30){this.charLength=4;break}}this.charReceived=n},i.prototype.end=function(e){var n="";if(e&&e.length&&(n=this.write(e)),this.charReceived){var l=this.charReceived,t=this.charBuffer,r=this.encoding;n+=t.slice(0,l).toString(r)}return n}},{buffer:137}],159:[function(e,n,l){function t(){throw new Error("tty.ReadStream is not implemented")}function r(){throw new Error("tty.ReadStream is not implemented")}l.isatty=function(){return!1},l.ReadStream=t,l.WriteStream=r},{}],160:[function(e,n){n.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],161:[function(e,n,l){(function(n,t){function r(e,n){var t={seen:[],stylize:o};return arguments.length>=3&&(t.depth=arguments[2]),arguments.length>=4&&(t.colors=arguments[3]),h(n)?t.showHidden=n:n&&l._extend(t,n),v(t.showHidden)&&(t.showHidden=!1),v(t.depth)&&(t.depth=2),v(t.colors)&&(t.colors=!1),v(t.customInspect)&&(t.customInspect=!0),t.colors&&(t.stylize=a),s(t,e,t.depth)}function a(e,n){var l=r.styles[n];return l?"["+r.colors[l][0]+"m"+e+"["+r.colors[l][1]+"m":e}function o(e){return e}function u(e){var n={};return e.forEach(function(e){n[e]=!0}),n}function s(e,n,t){if(e.customInspect&&n&&R(n.inspect)&&n.inspect!==l.inspect&&(!n.constructor||n.constructor.prototype!==n)){var r=n.inspect(t,e);return b(r)||(r=s(e,r,t)),r}var a=i(e,n);if(a)return a;var o=Object.keys(n),h=u(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(n)),w(n)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return c(n);if(0===o.length){if(R(n)){var m=n.name?": "+n.name:"";return e.stylize("[Function"+m+"]","special")}if(I(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(k(n))return e.stylize(Date.prototype.toString.call(n),"date");if(w(n))return c(n)}var y="",x=!1,_=["{","}"];if(g(n)&&(x=!0,_=["[","]"]),R(n)){var v=n.name?": "+n.name:"";y=" [Function"+v+"]"}if(I(n)&&(y=" "+RegExp.prototype.toString.call(n)),k(n)&&(y=" "+Date.prototype.toUTCString.call(n)),w(n)&&(y=" "+c(n)),0===o.length&&(!x||0==n.length))return _[0]+y+_[1];if(0>t)return I(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special");e.seen.push(n);var E;return E=x?d(e,n,t,h,o):o.map(function(l){return p(e,n,t,h,l,x)}),e.seen.pop(),f(E,y,_)}function i(e,n){if(v(n))return e.stylize("undefined","undefined");if(b(n)){var l="'"+JSON.stringify(n).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(l,"string")}return x(n)?e.stylize(""+n,"number"):h(n)?e.stylize(""+n,"boolean"):m(n)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,n,l,t,r){for(var a=[],o=0,u=n.length;u>o;++o)a.push(T(n,String(o))?p(e,n,l,t,String(o),!0):"");return r.forEach(function(r){r.match(/^\d+$/)||a.push(p(e,n,l,t,r,!0))}),a}function p(e,n,l,t,r,a){var o,u,i;if(i=Object.getOwnPropertyDescriptor(n,r)||{value:n[r]},i.get?u=i.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):i.set&&(u=e.stylize("[Setter]","special")),T(t,r)||(o="["+r+"]"),u||(e.seen.indexOf(i.value)<0?(u=m(l)?s(e,i.value,null):s(e,i.value,l-1),u.indexOf("\n")>-1&&(u=a?u.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+u.split("\n").map(function(e){return" "+e}).join("\n"))):u=e.stylize("[Circular]","special")),v(o)){if(a&&r.match(/^\d+$/))return u;o=JSON.stringify(""+r),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+u}function f(e,n,l){var t=0,r=e.reduce(function(e,n){return t++,n.indexOf("\n")>=0&&t++,e+n.replace(/\u001b\[\d\d?m/g,"").length+1},0);return r>60?l[0]+(""===n?"":n+"\n ")+" "+e.join(",\n ")+" "+l[1]:l[0]+n+" "+e.join(", ")+" "+l[1]}function g(e){return Array.isArray(e)}function h(e){return"boolean"==typeof e}function m(e){return null===e}function y(e){return null==e}function x(e){return"number"==typeof e}function b(e){return"string"==typeof e}function _(e){return"symbol"==typeof e}function v(e){return void 0===e}function I(e){return E(e)&&"[object RegExp]"===C(e)}function E(e){return"object"==typeof e&&null!==e}function k(e){return E(e)&&"[object Date]"===C(e)}function w(e){return E(e)&&("[object Error]"===C(e)||e instanceof Error)}function R(e){return"function"==typeof e}function S(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function C(e){return Object.prototype.toString.call(e)}function A(e){return 10>e?"0"+e.toString(10):e.toString(10)}function j(){var e=new Date,n=[A(e.getHours()),A(e.getMinutes()),A(e.getSeconds())].join(":");return[e.getDate(),M[e.getMonth()],n].join(" ")}function T(e,n){return Object.prototype.hasOwnProperty.call(e,n)}var L=/%[sdj%]/g;l.format=function(e){if(!b(e)){for(var n=[],l=0;l<arguments.length;l++)n.push(r(arguments[l]));return n.join(" ")}for(var l=1,t=arguments,a=t.length,o=String(e).replace(L,function(e){if("%%"===e)return"%";if(l>=a)return e;switch(e){case"%s":return String(t[l++]);case"%d":return Number(t[l++]);case"%j":try{return JSON.stringify(t[l++])}catch(n){return"[Circular]"}default:return e}}),u=t[l];a>l;u=t[++l])o+=m(u)||!E(u)?" "+u:" "+r(u);return o},l.deprecate=function(e,r){function a(){if(!o){if(n.throwDeprecation)throw new Error(r);n.traceDeprecation?console.trace(r):console.error(r),o=!0}return e.apply(this,arguments)}if(v(t.process))return function(){return l.deprecate(e,r).apply(this,arguments)};if(n.noDeprecation===!0)return e;var o=!1;return a};var P,O={};l.debuglog=function(e){if(v(P)&&(P=n.env.NODE_DEBUG||""),e=e.toUpperCase(),!O[e])if(new RegExp("\\b"+e+"\\b","i").test(P)){var t=n.pid;O[e]=function(){var n=l.format.apply(l,arguments);console.error("%s %d: %s",e,t,n)}}else O[e]=function(){};return O[e]},l.inspect=r,r.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},r.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},l.isArray=g,l.isBoolean=h,l.isNull=m,l.isNullOrUndefined=y,l.isNumber=x,l.isString=b,l.isSymbol=_,l.isUndefined=v,l.isRegExp=I,l.isObject=E,l.isDate=k,l.isError=w,l.isFunction=R,l.isPrimitive=S,l.isBuffer=e("./support/isBuffer");var M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];l.log=function(){console.log("%s - %s",j(),l.format.apply(l,arguments))},l.inherits=e("inherits"),l._extend=function(e,n){if(!n||!E(n))return e;for(var l=Object.keys(n),t=l.length;t--;)e[l[t]]=n[l[t]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":160,_process:145,inherits:142}],162:[function(e,n){"use strict";function l(e){var n=function l(){return t.apply(l,arguments)};return n._styles=e,n.__proto__=f,n}function t(){var e=arguments,n=e.length,l=0!==n&&String(arguments[0]);if(n>1)for(var t=1;n>t;t++)l+=" "+e[t];if(!d.enabled||!l)return l;for(var r=this._styles,a=0;a<r.length;a++){var u=o[r[a]];l=u.open+l.replace(u.closeRe,u.open)+u.close}return l}function r(){var e={};return Object.keys(p).forEach(function(n){e[n]={get:function(){return l([n])}}}),e}var a=e("escape-string-regexp"),o=e("ansi-styles"),u=e("strip-ansi"),s=e("has-ansi"),i=e("supports-color"),c=Object.defineProperties,d=n.exports,p=function(){var e={};return o.grey=o.gray,Object.keys(o).forEach(function(n){o[n].closeRe=new RegExp(a(o[n].close),"g"),e[n]={get:function(){return l(this._styles.concat(n))}}}),e}(),f=c(function(){},p);c(d,r()),d.styles=o,d.hasColor=s,d.stripColor=u,d.supportsColor=i,void 0===d.enabled&&(d.enabled=d.supportsColor)},{"ansi-styles":163,"escape-string-regexp":164,"has-ansi":165,"strip-ansi":167,"supports-color":169}],163:[function(e,n){"use strict";var l=n.exports,t={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]};Object.keys(t).forEach(function(e){var n=t[e],r=l[e]={};r.open="["+n[0]+"m",r.close="["+n[1]+"m"})},{}],164:[function(e,n){"use strict";var l=/[|\\{}()[\]^$+*?.]/g;n.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(l,"\\$&")}},{}],165:[function(e,n){"use strict";var l=e("ansi-regex"),t=new RegExp(l().source);n.exports=t.test.bind(t)},{"ansi-regex":166}],166:[function(e,n){"use strict";n.exports=function(){return/\u001b\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]/g}},{}],167:[function(e,n){"use strict";var l=e("ansi-regex")();n.exports=function(e){return"string"==typeof e?e.replace(l,""):e}},{"ansi-regex":168}],168:[function(e,n,l){arguments[4][166][0].apply(l,arguments)},{dup:166}],169:[function(e,n){(function(e){"use strict";n.exports=function(){return-1!==e.argv.indexOf("--no-color")?!1:-1!==e.argv.indexOf("--color")?!0:e.stdout&&!e.stdout.isTTY?!1:"win32"===e.platform?!0:"COLORTERM"in e.env?!0:"dumb"===e.env.TERM?!1:/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(e.env.TERM)?!0:!1}()}).call(this,e("_process"))},{_process:145}],170:[function(e,n){!function(e,l,t){"use strict";function r(e){return null!==e&&("object"==typeof e||"function"==typeof e)}function a(e){return"function"==typeof e}function o(e,n,l){e&&!hl(e=l?e:e[mn],Fl)&&Ll(e,Fl,n)}function u(e){return tl.call(e).slice(8,-1)}function s(e){var n,l;return e==t?e===t?"Undefined":"Null":"string"==typeof(l=(n=Cn(e))[Fl])?l:u(n)}function i(){for(var e=L(this),n=arguments.length,l=An(n),t=0,r=$l._,a=!1;n>t;)(l[t]=arguments[t++])===r&&(a=!0);return function(){var t,o=this,u=arguments.length,s=0,i=0;if(!a&&!u)return d(e,l,o);if(t=l.slice(),a)for(;n>s;s++)t[s]===r&&(t[s]=arguments[i++]);for(;u>i;)t.push(arguments[i++]);return d(e,t,o)}}function c(e,n,l){if(L(e),~l&&n===t)return e;switch(l){case 1:return function(l){return e.call(n,l)};case 2:return function(l,t){return e.call(n,l,t)};case 3:return function(l,t,r){return e.call(n,l,t,r)}}return function(){return e.apply(n,arguments)}}function d(e,n,l){var r=l===t;switch(0|n.length){case 0:return r?e():e.call(l);case 1:return r?e(n[0]):e.call(l,n[0]);case 2:return r?e(n[0],n[1]):e.call(l,n[0],n[1]);case 3:return r?e(n[0],n[1],n[2]):e.call(l,n[0],n[1],n[2]);case 4:return r?e(n[0],n[1],n[2],n[3]):e.call(l,n[0],n[1],n[2],n[3]);case 5:return r?e(n[0],n[1],n[2],n[3],n[4]):e.call(l,n[0],n[1],n[2],n[3],n[4])}return e.apply(l,n)}function p(e,n){var l=L(arguments.length<3?e:arguments[2])[mn],t=ol(r(l)?l:$n),a=al.call(e,t,n);return r(a)?a:t}function f(e){return ml(T(e))}function g(e){return e}function h(){return this}function m(e,n){return hl(e,n)?e[n]:void 0}function y(e){return P(e),fl?pl(e).concat(fl(e)):pl(e)}function x(e,n){for(var l,t=f(e),r=dl(t),a=r.length,o=0;a>o;)if(t[l=r[o++]]===n)return l}function b(e){return jn(e).split(",")}function _(e){var n=1==e,l=2==e,r=3==e,a=4==e,o=6==e,u=5==e||o;return function(s){for(var i,d,p=Cn(T(this)),f=arguments[1],g=ml(p),h=c(s,f,3),m=w(g.length),y=0,x=n?An(m):l?[]:t;m>y;y++)if((u||y in g)&&(i=g[y],d=h(i,y,p),e))if(n)x[y]=d;else if(d)switch(e){case 3:return!0;
case 5:return i;case 6:return y;case 2:x.push(i)}else if(a)return!1;return o?-1:r||a?a:x}}function v(e){return function(n){var l=f(this),t=w(l.length),r=R(arguments[1],t);if(e&&n!=n){for(;t>r;r++)if(E(l[r]))return e||r}else for(;t>r;r++)if((e||r in l)&&l[r]===n)return e||r;return!e&&-1}}function I(e,n){return"function"==typeof e?e:n}function E(e){return e!=e}function k(e){return isNaN(e)?0:Cl(e)}function w(e){return e>0?Rl(k(e),_l):0}function R(e,n){var e=k(e);return 0>e?wl(e+n,0):Rl(e,n)}function S(e){return e>9?e:"0"+e}function C(e,n,l){var t=r(n)?function(e){return n[e]}:n;return function(n){return jn(l?n:this).replace(e,t)}}function A(e){return function(n){var l,r,a=jn(T(this)),o=k(n),u=a.length;return 0>o||o>=u?e?"":t:(l=a.charCodeAt(o),55296>l||l>56319||o+1===u||(r=a.charCodeAt(o+1))<56320||r>57343?e?a.charAt(o):l:e?a.slice(o,o+2):(l-55296<<10)+(r-56320)+65536)}}function j(e,n,l){if(!e)throw Bn(l?n+l:n)}function T(e){if(e==t)throw Bn("Function called on null or undefined");return e}function L(e){return j(a(e),e," is not a function!"),e}function P(e){return j(r(e),e," is not an object!"),e}function O(e,n,l){j(e instanceof n,l,": use the 'new' operator!")}function M(e,n){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:n}}function D(e,n,l){return e[n]=l,e}function N(e){return jl?function(n,l,t){return il(n,l,M(e,t))}:D}function B(e){return pn+"("+e+")_"+(++Tl+Sl())[xn](36)}function F(e,n){return Dn&&Dn[e]||(n?Dn:Ol)(pn+el+e)}function V(e,n){for(var l in n)Ll(e,l,n[l]);return e}function U(e){(l||!ll(e))&&il(e,Nl,{configurable:!0,get:h})}function q(e,n){Ll(e,Bl,n),Vl&&Ll(e,kn,n)}function G(e,n,l,t){e[mn]=ol(t||Xl,{next:M(1,l)}),o(e,n+" Iterator")}function H(e,n,t,r){var a=e[mn],u=m(a,Bl)||m(a,kn)||r&&m(a,r)||t;if(l&&(q(a,u),u!==t)){var s=ul(u.call(new e));o(s,n+" Iterator",!0),hl(a,kn)&&q(s,h)}return Hl[n]=u,Hl[n+" Iterator"]=h,u}function X(e,n,l,t,r,a){function o(e){return function(){return new l(this,e)}}G(l,n,t);var u=o(ql+Gl),s=o(Gl);r==Gl?s=H(e,n,s,"values"):u=H(e,n,u,"entries"),r&&$(lt+Zl*Jl,n,{entries:u,keys:a?s:o(ql),values:s})}function W(e,n){return{value:n,done:!!e}}function J(n){var l=Cn(n),t=e[pn],r=(t&&t[En]||kn)in l;return r||Bl in l||hl(Hl,s(l))}function Y(n){var l=e[pn],t=n[l&&l[En]||kn],r=t||n[Bl]||Hl[s(n)];return P(r.call(n))}function z(e,n,l){return l?d(e,n):e(n)}function K(e,n,l,t){for(var r,a=Y(e),o=c(l,t,n?2:1);!(r=a.next()).done;)if(z(o,r.value,n)===!1)return}function $(n,t,r){var o,u,s,i,d=n&et,p=d?e:n&nt?e[t]:(e[t]||$n)[mn],f=d?Kl:Kl[t]||(Kl[t]={});d&&(r=t);for(o in r)u=!(n&Zl)&&p&&o in p&&(!a(p[o])||ll(p[o])),s=(u?p:r)[o],l||!d||a(p[o])?n&tt&&u?i=c(s,e):n&rt&&!l&&p[o]==s?(i=function(e){return this instanceof s?new s(e):s(e)},i[mn]=s[mn]):i=n<&&a(s)?c(rl,s):s:i=r[o],l&&p&&!u&&(d||n&at?p[o]=s:delete p[o]&&Ll(p,o,s)),f[o]!=s&&Ll(f,o,i)}var Q,Z,en="Object",nn="Function",ln="Array",tn="String",rn="Number",an="RegExp",on="Date",un="Map",sn="Set",cn="WeakMap",dn="WeakSet",pn="Symbol",fn="Promise",gn="Math",hn="Arguments",mn="prototype",yn="constructor",xn="toString",bn=xn+"Tag",_n="toLocaleString",vn="hasOwnProperty",In="forEach",En="iterator",kn="@@"+En,wn="process",Rn="createElement",Sn=e[nn],Cn=e[en],An=e[ln],jn=e[tn],Tn=e[rn],Ln=(e[an],e[on],e[un]),Pn=e[sn],On=e[cn],Mn=e[dn],Dn=e[pn],Nn=e[gn],Bn=e.TypeError,Fn=e.RangeError,Vn=e.setTimeout,Un=e.setImmediate,qn=e.clearImmediate,Gn=e.parseInt,Hn=e.isFinite,Xn=e[wn],Wn=Xn&&Xn.nextTick,Jn=e.document,Yn=Jn&&Jn.documentElement,zn=(e.navigator,e.define),Kn=An[mn],$n=Cn[mn],Qn=Sn[mn],Zn=1/0,el=".",nl="assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn",ll=c(/./.test,/\[native code\]\s*\}\s*$/,1),tl=$n[xn],rl=Qn.call,al=Qn.apply,ol=Cn.create,ul=Cn.getPrototypeOf,sl=Cn.setPrototypeOf,il=Cn.defineProperty,cl=(Cn.defineProperties,Cn.getOwnPropertyDescriptor),dl=Cn.keys,pl=Cn.getOwnPropertyNames,fl=Cn.getOwnPropertySymbols,gl=Cn.isFrozen,hl=c(rl,$n[vn],2),ml=Cn,yl=Cn.assign||function(e){for(var n=Cn(T(e)),l=arguments.length,t=1;l>t;)for(var r,a=ml(arguments[t++]),o=dl(a),u=o.length,s=0;u>s;)n[r=o[s++]]=a[r];return n},xl=Kn.push,bl=(Kn.unshift,Kn.slice,Kn.splice,Kn.indexOf,Kn[In]),_l=9007199254740991,vl=Nn.pow,Il=Nn.abs,El=Nn.ceil,kl=Nn.floor,wl=Nn.max,Rl=Nn.min,Sl=Nn.random,Cl=Nn.trunc||function(e){return(e>0?kl:El)(e)},Al="Reduce of empty object with no initial value",jl=!!function(){try{return 2==il({},"a",{get:function(){return 2}}).a}catch(e){}}(),Tl=0,Ll=N(1),Pl=Dn?D:Ll,Ol=Dn||B,Ml=F("unscopables"),Dl=Kn[Ml]||{},Nl=F("species"),Bl=F(En),Fl=F(bn),Vl=kn in Kn,Ul=Ol("iter"),ql=1,Gl=2,Hl={},Xl={},Wl=Bl in Kn,Jl="keys"in Kn&&!("next"in[].keys());q(Xl,h);var Yl,zl=u(Xn)==wn,Kl={},$l=l?e:Kl,Ql=e.core,Zl=1,et=2,nt=4,lt=8,tt=16,rt=32,at=64;"undefined"!=typeof n&&n.exports?n.exports=Kl:a(zn)&&zn.amd?zn(function(){return Kl}):Yl=!0,(Yl||l)&&(Kl.noConflict=function(){return e.core=Ql,Kl},e.core=Kl),!function(e,n,l,t){ll(Dn)||(Dn=function(n){j(!(this instanceof Dn),pn+" is not a "+yn);var r=B(n),a=Pl(ol(Dn[mn]),e,r);return l[r]=a,jl&&t&&il($n,r,{configurable:!0,set:function(e){Ll(this,r,e)}}),a},Ll(Dn[mn],xn,function(){return this[e]})),$(et+rt,{Symbol:Dn});var r={"for":function(e){return hl(n,e+="")?n[e]:n[e]=Dn(e)},iterator:Bl,keyFor:i.call(x,n),species:Nl,toStringTag:Fl=F(bn,!0),unscopables:Ml,pure:Ol,set:Pl,useSetter:function(){t=!0},useSimple:function(){t=!1}};bl.call(b("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(e){r[e]=F(e)}),$(nt,pn,r),o(Dn,pn),$(nt+Zl*!ll(Dn),en,{getOwnPropertyNames:function(e){for(var n,t=pl(f(e)),r=[],a=0;t.length>a;)hl(l,n=t[a++])||r.push(n);return r},getOwnPropertySymbols:function(e){for(var n,t=pl(f(e)),r=[],a=0;t.length>a;)hl(l,n=t[a++])&&r.push(l[n]);return r}})}(Ol("tag"),{},{},!0),!function(n){var t={assign:yl,is:function(e,n){return e===n?0!==e||1/e===1/n:e!=e&&n!=n}};"__proto__"in $n&&function(e,n){try{n=c(rl,cl($n,"__proto__").set,2),n({},Kn)}catch(l){e=!0}t.setPrototypeOf=sl=sl||function(l,t){return P(l),j(null===t||r(t),t,": can't set as prototype!"),e?l.__proto__=t:n(l,t),l}}(),$(nt,en,t),l&&(n[Fl]=el,u(n)!=el&&Ll($n,xn,function(){return"[object "+s(this)+"]"})),o(Nn,gn,!0),o(e.JSON,"JSON",!0)}({}),!function(){function e(e,n){var l=Cn[e],t=Kl[en][e],a=0,o={};if(!t||ll(t)){o[e]=1==n?function(e){return r(e)?l(e):e}:2==n?function(e){return r(e)?l(e):!0}:3==n?function(e){return r(e)?l(e):!1}:4==n?function(e,n){return l(f(e),n)}:function(e){return l(f(e))};try{l(el)}catch(u){a=1}$(nt+Zl*a,en,o)}}e("freeze",1),e("seal",1),e("preventExtensions",1),e("isFrozen",2),e("isSealed",2),e("isExtensible",3),e("getOwnPropertyDescriptor",4),e("getPrototypeOf"),e("keys"),e("getOwnPropertyNames")}(),!function(e){$(nt,rn,{EPSILON:vl(2,-52),isFinite:function(e){return"number"==typeof e&&Hn(e)},isInteger:e,isNaN:E,isSafeInteger:function(n){return e(n)&&Il(n)<=_l},MAX_SAFE_INTEGER:_l,MIN_SAFE_INTEGER:-_l,parseFloat:parseFloat,parseInt:Gn})}(Tn.isInteger||function(e){return!r(e)&&Hn(e)&&kl(e)===e}),!function(){function e(n){return Hn(n=+n)&&0!=n?0>n?-e(-n):r(n+a(n*n+1)):n}function n(e){return 0==(e=+e)?e:e>-1e-6&&1e-6>e?e+e*e/2:t(e)-1}var l=Nn.E,t=Nn.exp,r=Nn.log,a=Nn.sqrt,o=Nn.sign||function(e){return 0==(e=+e)||e!=e?e:0>e?-1:1};$(nt,gn,{acosh:function(e){return(e=+e)<1?0/0:Hn(e)?r(e/l+a(e+1)*a(e-1)/l)+1:e},asinh:e,atanh:function(e){return 0==(e=+e)?e:r((1+e)/(1-e))/2},cbrt:function(e){return o(e=+e)*vl(Il(e),1/3)},clz32:function(e){return(e>>>=0)?32-e[xn](2).length:32},cosh:function(e){return(t(e=+e)+t(-e))/2},expm1:n,fround:function(e){return new Float32Array([e])[0]},hypot:function(){for(var e,n=0,l=arguments.length,t=l,r=An(l),o=-Zn;l--;){if(e=r[l]=+arguments[l],e==Zn||e==-Zn)return Zn;e>o&&(o=e)}for(o=e||1;t--;)n+=vl(r[t]/o,2);return o*a(n)},imul:function(e,n){var l=65535,t=+e,r=+n,a=l&t,o=l&r;return 0|a*o+((l&t>>>16)*o+a*(l&r>>>16)<<16>>>0)},log1p:function(e){return(e=+e)>-1e-8&&1e-8>e?e-e*e/2:r(1+e)},log10:function(e){return r(e)/Nn.LN10},log2:function(e){return r(e)/Nn.LN2},sign:o,sinh:function(e){return Il(e=+e)<1?(n(e)-n(-e))/2:(t(e-1)-t(-e-1))*(l/2)},tanh:function(e){var l=n(e=+e),r=n(-e);return l==Zn?1:r==Zn?-1:(l-r)/(t(e)+t(-e))},trunc:Cl})}(),!function(e){function n(e){if(u(e)==an)throw Bn()}$(nt,tn,{fromCodePoint:function(){for(var n,l=[],t=arguments.length,r=0;t>r;){if(n=+arguments[r++],R(n,1114111)!==n)throw Fn(n+" is not a valid code point");l.push(65536>n?e(n):e(((n-=65536)>>10)+55296,n%1024+56320))}return l.join("")},raw:function(e){for(var n=f(e.raw),l=w(n.length),t=arguments.length,r=[],a=0;l>a;)r.push(jn(n[a++])),t>a&&r.push(jn(arguments[a]));return r.join("")}}),$(lt,tn,{codePointAt:A(!1),endsWith:function(e){n(e);var l=jn(T(this)),r=arguments[1],a=w(l.length),o=r===t?a:Rl(w(r),a);return e+="",l.slice(o-e.length,o)===e},includes:function(e){return n(e),!!~jn(T(this)).indexOf(e,arguments[1])},repeat:function(e){var n=jn(T(this)),l="",t=k(e);if(0>t||t==Zn)throw Fn("Count can't be negative");for(;t>0;(t>>>=1)&&(n+=n))1&t&&(l+=n);return l},startsWith:function(e){n(e);var l=jn(T(this)),t=w(Rl(arguments[1],l.length));return e+="",l.slice(t,t+e.length)===e}})}(jn.fromCharCode),!function(){$(nt,ln,{from:function(e){var n,l,r,a,o=Cn(T(e)),u=arguments[1],s=u!==t,i=s?c(u,arguments[2],2):t,d=0;if(J(o))for(r=Y(o),l=new(I(this,An));!(a=r.next()).done;d++)l[d]=s?i(a.value,d):a.value;else for(l=new(I(this,An))(n=w(o.length));n>d;d++)l[d]=s?i(o[d],d):o[d];return l.length=d,l},of:function(){for(var e=0,n=arguments.length,l=new(I(this,An))(n);n>e;)l[e]=arguments[e++];return l.length=n,l}}),$(lt,ln,{copyWithin:function(e,n){var l=Cn(T(this)),r=w(l.length),a=R(e,r),o=R(n,r),u=arguments[2],s=u===t?r:R(u,r),i=Rl(s-o,r-a),c=1;for(a>o&&o+i>a&&(c=-1,o=o+i-1,a=a+i-1);i-->0;)o in l?l[a]=l[o]:delete l[a],a+=c,o+=c;return l},fill:function(e){for(var n=Cn(T(this)),l=w(n.length),r=R(arguments[1],l),a=arguments[2],o=a===t?l:R(a,l);o>r;)n[r++]=e;return n},find:_(5),findIndex:_(6)}),l&&(bl.call(b("find,findIndex,fill,copyWithin,entries,keys,values"),function(e){Dl[e]=!0}),Ml in Kn||Ll(Kn,Ml,Dl)),U(An)}(),!function(e){X(An,ln,function(e,n){Pl(this,Ul,{o:f(e),i:0,k:n})},function(){var e=this[Ul],n=e.o,l=e.k,r=e.i++;return!n||r>=n.length?(e.o=t,W(1)):l==ql?W(0,r):l==Gl?W(0,n[r]):W(0,[r,n[r]])},Gl),Hl[hn]=Hl[ln],X(jn,tn,function(e){Pl(this,Ul,{o:jn(e),i:0})},function(){var n,l=this[Ul],t=l.o,r=l.i;return r>=t.length?W(1):(n=e.call(t,r),l.i+=n.length,W(0,n))})}(A(!0)),a(Un)&&a(qn)||function(n){function l(e){if(hl(h,e)){var n=h[e];delete h[e],n()}}function t(e){l(e.data)}var r,o,u,s=e.postMessage,p=e.addEventListener,f=e.MessageChannel,g=0,h={};Un=function(e){for(var n=[],l=1;arguments.length>l;)n.push(arguments[l++]);return h[++g]=function(){d(a(e)?e:Sn(e),n)},r(g),g},qn=function(e){delete h[e]},zl?r=function(e){Wn(i.call(l,e))}:p&&a(s)&&!e.importScripts?(r=function(e){s(e,"*")},p("message",t,!1)):a(f)?(o=new f,u=o.port2,o.port1.onmessage=t,r=c(u.postMessage,u,1)):r=Jn&&n in Jn[Rn]("script")?function(e){Yn.appendChild(Jn[Rn]("script"))[n]=function(){Yn.removeChild(this),l(e)}}:function(e){Vn(l,0,e)}}("onreadystatechange"),$(et+tt,{setImmediate:Un,clearImmediate:qn}),!function(e,n){a(e)&&a(e.resolve)&&e.resolve(n=new e(function(){}))==n||function(n,l){function o(e){var n;return r(e)&&(n=e.then),a(n)?n:!1}function u(e){var l=e.chain;l.length&&n(function(){for(var n=e.msg,t=1==e.state,r=0;l.length>r;)!function(e){var l,r,a=t?e.ok:e.fail;try{a?(l=a===!0?n:a(n),l===e.P?e.rej(Bn(fn+"-chain cycle")):(r=o(l))?r.call(l,e.res,e.rej):e.res(l)):e.rej(n)}catch(u){e.rej(u)}}(l[r++]);l.length=0})}function s(e){var n,l,t=this;if(!t.done){t.done=!0,t=t.def||t;try{(n=o(e))?(l={def:t,done:!1},n.call(e,c(s,l,1),c(i,l,1))):(t.msg=e,t.state=1,u(t))}catch(r){i.call(l||{def:t,done:!1},r)}}}function i(e){var n=this;n.done||(n.done=!0,n=n.def||n,n.msg=e,n.state=2,u(n))}function d(e){var n=P(e)[Nl];return n!=t?n:e}e=function(n){L(n),O(this,e,fn);var r={chain:[],state:0,done:!1,msg:t};Ll(this,l,r);try{n(c(s,r,1),c(i,r,1))}catch(a){i.call(r,a)}},V(e[mn],{then:function(n,r){var o=P(P(this)[yn])[Nl],s={ok:a(n)?n:!0,fail:a(r)?r:!1},i=s.P=new(o!=t?o:e)(function(e,n){s.res=L(e),s.rej=L(n)}),c=this[l];return c.chain.push(s),c.state&&u(c),i},"catch":function(e){return this.then(t,e)}}),V(e,{all:function(e){var n=d(this),l=[];return new n(function(t,r){K(e,!1,xl,l);var a=l.length,o=An(a);a?bl.call(l,function(e,l){n.resolve(e).then(function(e){o[l]=e,--a||t(o)},r)}):t(o)})},race:function(e){var n=d(this);return new n(function(l,t){K(e,!1,function(e){n.resolve(e).then(l,t)})})},reject:function(e){return new(d(this))(function(n,l){l(e)})},resolve:function(e){return r(e)&&l in e&&ul(e)===this[mn]?e:new(d(this))(function(n){n(e)})}})}(Wn||Un,Ol("def")),o(e,fn),U(e),$(et+Zl*!ll(e),{Promise:e})}(e[fn]),!function(){function e(e,n,r,a,u,s){function i(e,n){return n!=t&&K(n,u,e[f],e),e}function c(e,n){var t=g[e];l&&(g[e]=function(e,l){var r=t.call(this,0===e?0:e,l);return n?this:r})}var f=u?"set":"add",g=e&&e[mn],b={};if(ll(e)&&(s||!Jl&&hl(g,In)&&hl(g,"entries"))){var _,v=e,I=new e,E=I[f](s?{}:-0,1);Wl&&e.length||(e=function(l){return O(this,e,n),i(new v,l)},e[mn]=g,l&&(g[yn]=e)),s||I[In](function(e,n){_=1/n===-Zn}),_&&(c("delete"),c("has"),u&&c("get")),(_||E!==I)&&c(f,!0)}else e=s?function(l){O(this,e,n),Pl(this,d,x++),i(this,l)}:function(l){var r=this;O(r,e,n),Pl(r,p,ol(null)),Pl(r,y,0),Pl(r,h,t),Pl(r,m,t),i(r,l)},V(V(e[mn],r),a),s||il(e[mn],"size",{get:function(){return T(this[y])}});return o(e,n),U(e),b[n]=e,$(et+rt+Zl*!ll(e),b),s||X(e,n,function(e,n){Pl(this,Ul,{o:e,k:n})},function(){for(var e=this[Ul],n=e.k,l=e.l;l&&l.r;)l=l.p;return e.o&&(e.l=l=l?l.n:e.o[m])?n==ql?W(0,l.k):n==Gl?W(0,l.v):W(0,[l.k,l.v]):(e.o=t,W(1))},u?ql+Gl:Gl,!u),e}function n(e,n){if(!r(e))return("string"==typeof e?"S":"P")+e;if(gl(e))return"F";if(!hl(e,d)){if(!n)return"E";Ll(e,d,++x)}return"O"+e[d]}function a(e,l){var t,r=n(l);if("F"!=r)return e[p][r];for(t=e[m];t;t=t.n)if(t.k==l)return t}function u(e,l,r){var o,u,s=a(e,l);return s?s.v=r:(e[h]=s={i:u=n(l,!0),k:l,v:r,p:o=e[h],n:t,r:!1},e[m]||(e[m]=s),o&&(o.n=s),e[y]++,"F"!=u&&(e[p][u]=s)),e}function s(e,n,l){return gl(P(n))?i(e).set(n,l):(hl(n,f)||Ll(n,f,{}),n[f][e[d]]=l),e}function i(e){return e[g]||Ll(e,g,new Ln)[g]}var d=Ol("uid"),p=Ol("O1"),f=Ol("weak"),g=Ol("leak"),h=Ol("last"),m=Ol("first"),y=jl?Ol("size"):"size",x=0,_={},v={clear:function(){for(var e=this,n=e[p],l=e[m];l;l=l.n)l.r=!0,l.p&&(l.p=l.p.n=t),delete n[l.i];e[m]=e[h]=t,e[y]=0},"delete":function(e){var n=this,l=a(n,e);if(l){var t=l.n,r=l.p;delete n[p][l.i],l.r=!0,r&&(r.n=t),t&&(t.p=r),n[m]==l&&(n[m]=t),n[h]==l&&(n[h]=r),n[y]--}return!!l},forEach:function(e){for(var n,l=c(e,arguments[1],3);n=n?n.n:this[m];)for(l(n.v,n.k,this);n&&n.r;)n=n.p},has:function(e){return!!a(this,e)}};Ln=e(Ln,un,{get:function(e){var n=a(this,e);return n&&n.v},set:function(e,n){return u(this,0===e?0:e,n)}},v,!0),Pn=e(Pn,sn,{add:function(e){return u(this,e=0===e?0:e,e)}},v);var I={"delete":function(e){return r(e)?gl(e)?i(this)["delete"](e):hl(e,f)&&hl(e[f],this[d])&&delete e[f][this[d]]:!1},has:function(e){return r(e)?gl(e)?i(this).has(e):hl(e,f)&&hl(e[f],this[d]):!1}};On=e(On,cn,{get:function(e){if(r(e)){if(gl(e))return i(this).get(e);if(hl(e,f))return e[f][this[d]]}},set:function(e,n){return s(this,e,n)}},I,!0,!0),l&&7!=(new On).set(Cn.freeze(_),7).get(_)&&bl.call(b("delete,has,get,set"),function(e){var n=On[mn][e];On[mn][e]=function(l,t){if(r(l)&&gl(l)){var a=i(this)[e](l,t);return"set"==e?this:a}return n.call(this,l,t)}}),Mn=e(Mn,dn,{add:function(e){return s(this,e,!0)}},I,!1,!0)}(),!function(){function e(e){var n,l=[];for(n in e)l.push(n);Pl(this,Ul,{o:e,a:l,i:0})}function n(e){return function(n){P(n);try{return e.apply(t,arguments),!0}catch(l){return!1}}}function l(e,n){var a,o=arguments.length<3?e:arguments[2],u=cl(P(e),n);return u?hl(u,"value")?u.value:u.get===t?t:u.get.call(o):r(a=ul(e))?l(a,n,o):t}function a(e,n,l){var o,u,s=arguments.length<4?e:arguments[3],i=cl(P(e),n);if(!i){if(r(u=ul(e)))return a(u,n,l,s);i=M(0)}return hl(i,"value")?i.writable!==!1&&r(s)?(o=cl(s,n)||M(0),o.value=l,il(s,n,o),!0):!1:i.set===t?!1:(i.set.call(s,l),!0)}G(e,en,function(){var e,n=this[Ul],l=n.a;do if(n.i>=l.length)return W(1);while(!((e=l[n.i++])in n.o));return W(0,e)});var o=Cn.isExtensible||g,u={apply:c(rl,al,3),construct:p,defineProperty:n(il),deleteProperty:function(e,n){var l=cl(P(e),n);return l&&!l.configurable?!1:delete e[n]},enumerate:function(n){return new e(P(n))},get:l,getOwnPropertyDescriptor:function(e,n){return cl(P(e),n)},getPrototypeOf:function(e){return ul(P(e))},has:function(e,n){return n in e},isExtensible:function(e){return!!o(P(e))},ownKeys:y,preventExtensions:n(Cn.preventExtensions||g),set:a};sl&&(u.setPrototypeOf=function(e,n){return sl(P(e),n),!0}),$(et,{Reflect:{}}),$(nt,"Reflect",u)}(),!function(){function e(e){return function(n){var l,t=f(n),r=dl(n),a=r.length,o=0,u=An(a);if(e)for(;a>o;)u[o]=[l=r[o++],t[l]];else for(;a>o;)u[o]=t[r[o++]];return u}}$(lt,ln,{includes:v(!0)}),$(lt,tn,{at:A(!0)}),$(nt,en,{values:e(!1),entries:e(!0)}),$(nt,an,{escape:C(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",!0)})}(),!function(e){function n(e){if(e){var n=e[mn];Ll(n,Q,n.get),Ll(n,l,n.set),Ll(n,t,n["delete"])}}Q=F(e+"Get",!0);var l=F(e+sn,!0),t=F(e+"Delete",!0);$(nt,pn,{referenceGet:Q,referenceSet:l,referenceDelete:t}),Ll(Qn,Q,h),n(Ln),n(On)}("reference"),!function(e){function n(e,n){Pl(this,Ul,{o:f(e),a:dl(e),i:0,k:n})}function l(e){return function(l){return new n(l,e)}}function a(e){var n=1==e,l=4==e;return function(r,a,o){var u,s,i,d=c(a,o,3),p=f(r),g=n||7==e||2==e?new(I(this,Z)):t;for(u in p)if(hl(p,u)&&(s=p[u],i=d(s,u,r),e))if(n)g[u]=i;else if(i)switch(e){case 2:g[u]=s;break;case 3:return!0;case 5:return s;case 6:return u;case 7:g[i[0]]=i[1]}else if(l)return!1;return 3==e||l?l:g}}function o(e){return function(n,l,r){L(l);var a,o,u,s=f(n),i=dl(s),c=i.length,d=0;for(e?a=r==t?new(I(this,Z)):Cn(r):arguments.length<3?(j(c,Al),a=s[i[d++]]):a=Cn(r);c>d;)if(hl(s,o=i[d++]))if(u=l(a,s[o],o,n),e){if(u===!1)break}else a=u;return a}}function u(e,n){return(n==n?x(e,n):s(e,E))!==t}Z=function(e){var n=ol(null);if(e!=t)if(J(e))for(var l,r,a=Y(e);!(l=a.next()).done;)r=l.value,n[r[0]]=r[1];else yl(n,e);return n},Z[mn]=null,G(n,e,function(){var e,n=this[Ul],l=n.o,r=n.a,a=n.k;do if(n.i>=r.length)return n.o=t,W(1);while(!hl(l,e=r[n.i++]));return a==ql?W(0,e):a==Gl?W(0,l[e]):W(0,[e,l[e]])});var s=a(6),i={keys:l(ql),values:l(Gl),entries:l(ql+Gl),forEach:a(0),map:a(1),filter:a(2),some:a(3),every:a(4),find:a(5),findKey:s,mapPairs:a(7),reduce:o(!1),turn:o(!0),keyOf:x,includes:u,has:hl,get:m,set:N(0),isDict:function(e){return r(e)&&ul(e)===Z[mn]}};if(Q)for(var p in i)!function(e){function n(){for(var n=[this],l=0;l<arguments.length;)n.push(arguments[l++]);return d(e,n)}e[Q]=function(){return n}}(i[p]);$(et+Zl,{Dict:V(Z,i)})}("Dict"),!function(e,n){function l(n,t){return this instanceof l?(this[Ul]=Y(n),void(this[e]=!!t)):new l(n,t)}function r(l){function t(l,t,r){this[Ul]=Y(l),this[e]=l[e],this[n]=c(t,r,l[e]?2:1)}return G(t,"Chain",l,a),q(t[mn],h),t}G(l,"Wrapper",function(){return this[Ul].next()});var a=l[mn];q(a,function(){return this[Ul]});var o=r(function(){var l=this[Ul].next();return l.done?l:W(0,z(this[n],l.value,this[e]))}),u=r(function(){for(;;){var l=this[Ul].next();if(l.done||z(this[n],l.value,this[e]))return l}});V(a,{of:function(n,l){K(this,this[e],n,l)},array:function(e,n){var l=[];return K(e!=t?this.map(e,n):this,!1,xl,l),l},filter:function(e,n){return new u(this,e,n)},map:function(e,n){return new o(this,e,n)}}),l.isIterable=J,l.getIterator=Y,$(et+Zl,{$for:l})}("entries",Ol("fn")),$(et+Zl,{delay:function(e){return new Promise(function(n){Vn(n,e,!0)})}}),!function(e,n){function l(l){var r=this,a={};return Ll(r,e,function(e){return e!==t&&e in r?hl(a,e)?a[e]:a[e]=c(r[e],r,-1):n.call(r)})[e](l)}Kl._=$l._=$l._||{},$(lt+Zl,nn,{part:i,only:function(e,n){var l=L(this),t=w(e),r=arguments.length>1;return function(){for(var e=Rl(t,arguments.length),a=An(e),o=0;e>o;)a[o]=arguments[o++];return d(l,a,r?n:this)}}}),Ll($l._,xn,function(){return e}),Ll($n,e,l),jl||Ll(Kn,e,l)}(jl?B("tie"):_n,$n[_n]),!function(){function e(e,n){for(var l,t=y(f(n)),r=t.length,a=0;r>a;)il(e,l=t[a++],cl(n,l));return e}$(nt+Zl,en,{isObject:r,classof:s,define:e,make:function(n,l){return e(ol(n),l)}})}(),$(lt+Zl,ln,{turn:function(e,n){L(e);for(var l=n==t?[]:Cn(n),r=ml(this),a=w(r.length),o=0;a>o&&e(l,r[o],o++,this)!==!1;);return l}}),l&&(Dl.turn=!0),!function(e){function n(e){Pl(this,Ul,{l:w(e),i:0})}G(n,rn,function(){var e=this[Ul],n=e.i++;return n<e.l?W(0,n):W(1)}),H(Tn,rn,function(){return new n(this)}),e.random=function(e){var n=+this,l=e==t?0:+e,r=Rl(n,l);return Sl()*(wl(n,l)-r)+r},bl.call(b("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc"),function(n){var l=Nn[n];l&&(e[n]=function(){for(var e=[+this],n=0;arguments.length>n;)e.push(arguments[n++]);return d(l,e)})}),$(lt+Zl,rn,e)}({}),!function(){var e,n={"&":"&","<":"<",">":">",'"':""","'":"'"},l={};for(e in n)l[n[e]]=e;$(lt+Zl,tn,{escapeHTML:C(/[&<>"']/g,n),unescapeHTML:C(/&(?:amp|lt|gt|quot|apos);/g,l)})}(),!function(e,n,l,t,r,a,o,u,s){function i(n){return function(i,c){function d(e){return p[n+e]()}var p=this,f=l[hl(l,c)?c:t];return jn(i).replace(e,function(e){switch(e){case"s":return d(r);case"ss":return S(d(r));case"m":return d(a);case"mm":return S(d(a));case"h":return d(o);case"hh":return S(d(o));case"D":return d(on);case"DD":return S(d(on));case"W":return f[0][d("Day")];case"N":return d(u)+1;case"NN":return S(d(u)+1);case"M":return f[2][d(u)];case"MM":return f[1][d(u)];case"Y":return d(s);case"YY":return S(d(s)%100)}return e})}}function c(e,t){function r(e){var l=[];return bl.call(b(t.months),function(t){l.push(t.replace(n,"$"+e))}),l}return l[e]=[b(t.weekdays),r(1),r(2)],Kl}$(lt+Zl,on,{format:i("get"),formatUTC:i("getUTC")}),c(t,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"}),c("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"}),Kl.locale=function(e){return hl(l,e)?t=e:t},Kl.addLocale=c}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear"),$(et+Zl,{global:e}),!function(e){function n(n,l){bl.call(b(n),function(n){n in Kn&&(e[n]=c(rl,Kn[n],l))})}n("pop,reverse,shift,keys,values,entries",1),n("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3),n("join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill,turn"),$(nt,ln,e)}({}),!function(e){!l||!e||Bl in e[mn]||Ll(e[mn],Bl,Hl[ln]),Hl.NodeList=Hl[ln]}(e.NodeList),!function(e,n,l){bl.call(b(nl),function(t){e[t]=function(){return l&&t in n?al.call(n[t],n,arguments):void 0}}),$(et+Zl,{log:yl(e.log,e,{enable:function(){l=!0},disable:function(){l=!1}})})}({},e.console||{},!0)}("undefined"!=typeof self&&self.Math===Math?self:Function("return this")(),!1)},{}],171:[function(e,n,l){function t(){return l.colors[c++%l.colors.length]}function r(e){function n(){}function r(){var e=r,n=+new Date,a=n-(i||n);e.diff=a,e.prev=i,e.curr=n,i=n,null==e.useColors&&(e.useColors=l.useColors()),null==e.color&&e.useColors&&(e.color=t());var o=Array.prototype.slice.call(arguments);o[0]=l.coerce(o[0]),"string"!=typeof o[0]&&(o=["%o"].concat(o));var u=0;o[0]=o[0].replace(/%([a-z%])/g,function(n,t){if("%%"===n)return n;u++;var r=l.formatters[t];if("function"==typeof r){var a=o[u];n=r.call(e,a),o.splice(u,1),u--}return n}),"function"==typeof l.formatArgs&&(o=l.formatArgs.apply(e,o));var s=r.log||l.log||console.log.bind(console);s.apply(e,o)}n.enabled=!1,r.enabled=!0;var a=l.enabled(e)?r:n;return a.namespace=e,a}function a(e){l.save(e);for(var n=(e||"").split(/[\s,]+/),t=n.length,r=0;t>r;r++)n[r]&&(e=n[r].replace(/\*/g,".*?"),"-"===e[0]?l.skips.push(new RegExp("^"+e.substr(1)+"$")):l.names.push(new RegExp("^"+e+"$")))}function o(){l.enable("")}function u(e){var n,t;for(n=0,t=l.skips.length;t>n;n++)if(l.skips[n].test(e))return!1;for(n=0,t=l.names.length;t>n;n++)if(l.names[n].test(e))return!0;return!1}function s(e){return e instanceof Error?e.stack||e.message:e}l=n.exports=r,l.coerce=s,l.disable=o,l.enable=a,l.enabled=u,l.humanize=e("ms"),l.names=[],l.skips=[],l.formatters={};var i,c=0},{ms:173}],172:[function(e,n,l){(function(t){function r(){var e=(t.env.DEBUG_COLORS||"").trim().toLowerCase();return 0===e.length?c.isatty(p):"0"!==e&&"no"!==e&&"false"!==e&&"disabled"!==e}function a(){var e=arguments,n=this.useColors,t=this.namespace;if(n){var r=this.color;e[0]=" [9"+r+"m"+t+" [0m"+e[0]+"[3"+r+"m +"+l.humanize(this.diff)+"[0m"}else e[0]=(new Date).toUTCString()+" "+t+" "+e[0];return e}function o(){return f.write(d.format.apply(this,arguments)+"\n")}function u(e){null==e?delete t.env.DEBUG:t.env.DEBUG=e}function s(){return t.env.DEBUG}function i(n){var l,r=t.binding("tty_wrap");switch(r.guessHandleType(n)){case"TTY":l=new c.WriteStream(n),l._type="tty",l._handle&&l._handle.unref&&l._handle.unref();break;case"FILE":var a=e("fs");l=new a.SyncWriteStream(n,{autoClose:!1}),l._type="fs";break;case"PIPE":case"TCP":var o=e("net");l=new o.Socket({fd:n,readable:!1,writable:!0}),l.readable=!1,l.read=null,l._type="pipe",l._handle&&l._handle.unref&&l._handle.unref();break;default:throw new Error("Implement me. Unknown stream file type!")}return l.fd=n,l._isStdio=!0,l}var c=e("tty"),d=e("util");l=n.exports=e("./debug"),l.log=o,l.formatArgs=a,l.save=u,l.load=s,l.useColors=r,l.colors=[6,2,3,4,5,1];var p=parseInt(t.env.DEBUG_FD,10)||2,f=1===p?t.stdout:2===p?t.stderr:i(p),g=4===d.inspect.length?function(e,n){return d.inspect(e,void 0,void 0,n)}:function(e,n){return d.inspect(e,{colors:n})};l.formatters.o=function(e){return g(e,this.useColors).replace(/\s*\n\s*/g," ")},l.enable(s())}).call(this,e("_process"))},{"./debug":171,_process:145,fs:135,net:135,tty:159,util:161}],173:[function(e,n){function l(e){var n=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(e);if(n){var l=parseFloat(n[1]),t=(n[2]||"ms").toLowerCase();switch(t){case"years":case"year":case"y":return l*c;case"days":case"day":case"d":return l*i;case"hours":case"hour":case"h":return l*s;case"minutes":case"minute":case"m":return l*u;case"seconds":case"second":case"s":return l*o;case"ms":return l}}}function t(e){return e>=i?Math.round(e/i)+"d":e>=s?Math.round(e/s)+"h":e>=u?Math.round(e/u)+"m":e>=o?Math.round(e/o)+"s":e+"ms"}function r(e){return a(e,i,"day")||a(e,s,"hour")||a(e,u,"minute")||a(e,o,"second")||e+" ms"}function a(e,n,l){return n>e?void 0:1.5*n>e?Math.floor(e/n)+" "+l:Math.ceil(e/n)+" "+l+"s"}var o=1e3,u=60*o,s=60*u,i=24*s,c=365.25*i;n.exports=function(e,n){return n=n||{},"string"==typeof e?l(e):n.long?r(e):t(e)}},{}],174:[function(e,n){"use strict";function l(e){var n=0,l=0,t=0;for(var r in e){var a=e[r],o=a[0],u=a[1];(o>l||o===l&&u>t)&&(l=o,t=u,n=+r)}return n}var t=e("repeating"),r=/^(?:( )+|\t+)/;n.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");var n,a,o=0,u=0,s=0,i={};e.split(/\n/g).forEach(function(e){if(e){var l,t=e.match(r);t?(l=t[0].length,t[1]?u++:o++):l=0;var c=l-s;s=l,c?(a=c>0,n=i[a?c:-c],n?n[0]++:n=i[c]=[1,0]):n&&(n[1]+=+a)}});var c,d,p=l(i);return p?u>=o?(c="space",d=t(" ",p)):(c="tab",d=t(" ",p)):(c=null,d=""),{amount:p,type:c,indent:d}}},{repeating:300}],175:[function(n,l,t){!function(n,l){"use strict";"function"==typeof e&&e.amd?e(["exports"],l):l("undefined"!=typeof t?t:n.estraverse={})}(this,function r(e){"use strict";function n(){}function l(e){var n,t,r={};for(n in e)e.hasOwnProperty(n)&&(t=e[n],r[n]="object"==typeof t&&null!==t?l(t):t);return r}function t(e){var n,l={};for(n in e)e.hasOwnProperty(n)&&(l[n]=e[n]);return l}function a(e,n){var l,t,r,a;for(t=e.length,r=0;t;)l=t>>>1,a=r+l,n(e[a])?t=l:(r=a+1,t-=l+1);return r}function o(e,n){var l,t,r,a;for(t=e.length,r=0;t;)l=t>>>1,a=r+l,n(e[a])?(r=a+1,t-=l+1):t=l;return r}function u(e,n){return I(n).forEach(function(l){e[l]=n[l]}),e}function s(e,n){this.parent=e,this.key=n}function i(e,n,l,t){this.node=e,this.path=n,this.wrap=l,this.ref=t}function c(){}function d(e){return null==e?!1:"object"==typeof e&&"string"==typeof e.type}function p(e,n){return(e===y.ObjectExpression||e===y.ObjectPattern)&&"properties"===n}function f(e,n){var l=new c;return l.traverse(e,n)}function g(e,n){var l=new c;return l.replace(e,n)}function h(e,n){var l;return l=a(n,function(n){return n.range[0]>e.range[0]}),e.extendedRange=[e.range[0],e.range[1]],l!==n.length&&(e.extendedRange[1]=n[l].range[0]),l-=1,l>=0&&(e.extendedRange[0]=n[l].range[1]),e}function m(e,n,t){var r,a,o,u,s=[];if(!e.range)throw new Error("attachComments needs range information");if(!t.length){if(n.length){for(o=0,a=n.length;a>o;o+=1)r=l(n[o]),r.extendedRange=[0,e.range[0]],s.push(r);e.leadingComments=s}return e}for(o=0,a=n.length;a>o;o+=1)s.push(h(l(n[o]),t));return u=0,f(e,{enter:function(e){for(var n;u<s.length&&(n=s[u],!(n.extendedRange[1]>e.range[0]));)n.extendedRange[1]===e.range[0]?(e.leadingComments||(e.leadingComments=[]),e.leadingComments.push(n),s.splice(u,1)):u+=1;return u===s.length?b.Break:s[u].extendedRange[0]>e.range[1]?b.Skip:void 0}}),u=0,f(e,{leave:function(e){for(var n;u<s.length&&(n=s[u],!(e.range[1]<n.extendedRange[0]));)e.range[1]===n.extendedRange[0]?(e.trailingComments||(e.trailingComments=[]),e.trailingComments.push(n),s.splice(u,1)):u+=1;return u===s.length?b.Break:s[u].extendedRange[0]>e.range[1]?b.Skip:void 0}}),e}var y,x,b,_,v,I,E,k,w;return x=Array.isArray,x||(x=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),n(t),n(o),v=Object.create||function(){function e(){}return function(n){return e.prototype=n,new e}}(),I=Object.keys||function(e){var n,l=[];for(n in e)l.push(n);return l},y={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},_={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},E={},k={},w={},b={Break:E,Skip:k,Remove:w},s.prototype.replace=function(e){this.parent[this.key]=e
},s.prototype.remove=function(){return x(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},c.prototype.path=function(){function e(e,n){if(x(n))for(t=0,r=n.length;r>t;++t)e.push(n[t]);else e.push(n)}var n,l,t,r,a,o;if(!this.__current.path)return null;for(a=[],n=2,l=this.__leavelist.length;l>n;++n)o=this.__leavelist[n],e(a,o.path);return e(a,this.__current.path),a},c.prototype.type=function(){var e=this.current();return e.type||this.__current.wrap},c.prototype.parents=function(){var e,n,l;for(l=[],e=1,n=this.__leavelist.length;n>e;++e)l.push(this.__leavelist[e].node);return l},c.prototype.current=function(){return this.__current.node},c.prototype.__execute=function(e,n){var l,t;return t=void 0,l=this.__current,this.__current=n,this.__state=null,e&&(t=e.call(this,n.node,this.__leavelist[this.__leavelist.length-1].node)),this.__current=l,t},c.prototype.notify=function(e){this.__state=e},c.prototype.skip=function(){this.notify(k)},c.prototype["break"]=function(){this.notify(E)},c.prototype.remove=function(){this.notify(w)},c.prototype.__initialize=function(e,n){this.visitor=n,this.root=e,this.__worklist=[],this.__leavelist=[],this.__current=null,this.__state=null,this.__fallback="iteration"===n.fallback,this.__keys=_,n.keys&&(this.__keys=u(v(this.__keys),n.keys))},c.prototype.traverse=function(e,n){var l,t,r,a,o,u,s,c,f,g,h,m;for(this.__initialize(e,n),m={},l=this.__worklist,t=this.__leavelist,l.push(new i(e,null,null,null)),t.push(new i(null,null,null,null));l.length;)if(r=l.pop(),r!==m){if(r.node){if(u=this.__execute(n.enter,r),this.__state===E||u===E)return;if(l.push(m),t.push(r),this.__state===k||u===k)continue;if(a=r.node,o=r.wrap||a.type,g=this.__keys[o],!g){if(!this.__fallback)throw new Error("Unknown node type "+o+".");g=I(a)}for(c=g.length;(c-=1)>=0;)if(s=g[c],h=a[s])if(x(h)){for(f=h.length;(f-=1)>=0;)if(h[f]){if(p(o,g[c]))r=new i(h[f],[s,f],"Property",null);else{if(!d(h[f]))continue;r=new i(h[f],[s,f],null,null)}l.push(r)}}else d(h)&&l.push(new i(h,s,null,null))}}else if(r=t.pop(),u=this.__execute(n.leave,r),this.__state===E||u===E)return},c.prototype.replace=function(e,n){function l(e){var n,l,r,a;if(e.ref.remove())for(l=e.ref.key,a=e.ref.parent,n=t.length;n--;)if(r=t[n],r.ref&&r.ref.parent===a){if(r.ref.key<l)break;--r.ref.key}}var t,r,a,o,u,c,f,g,h,m,y,b,_;for(this.__initialize(e,n),y={},t=this.__worklist,r=this.__leavelist,b={root:e},c=new i(e,null,null,new s(b,"root")),t.push(c),r.push(c);t.length;)if(c=t.pop(),c!==y){if(u=this.__execute(n.enter,c),void 0!==u&&u!==E&&u!==k&&u!==w&&(c.ref.replace(u),c.node=u),(this.__state===w||u===w)&&(l(c),c.node=null),this.__state===E||u===E)return b.root;if(a=c.node,a&&(t.push(y),r.push(c),this.__state!==k&&u!==k)){if(o=c.wrap||a.type,h=this.__keys[o],!h){if(!this.__fallback)throw new Error("Unknown node type "+o+".");h=I(a)}for(f=h.length;(f-=1)>=0;)if(_=h[f],m=a[_])if(x(m)){for(g=m.length;(g-=1)>=0;)if(m[g]){if(p(o,h[f]))c=new i(m[g],[_,g],"Property",new s(m,g));else{if(!d(m[g]))continue;c=new i(m[g],[_,g],null,new s(m,g))}t.push(c)}}else d(m)&&t.push(new i(m,_,null,new s(a,_)))}}else if(c=r.pop(),u=this.__execute(n.leave,c),void 0!==u&&u!==E&&u!==k&&u!==w&&c.ref.replace(u),(this.__state===w||u===w)&&l(c),this.__state===E||u===E)return b.root;return b.root},e.version="1.8.1-dev",e.Syntax=y,e.traverse=f,e.replace=g,e.attachComments=m,e.VisitorKeys=_,e.VisitorOption=b,e.Controller=c,e.cloneEnvironment=function(){return r({})},e})},{}],176:[function(e,n){!function(){"use strict";function e(e){if(null==e)return!1;switch(e.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return!0}return!1}function l(e){if(null==e)return!1;switch(e.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return!0}return!1}function t(e){if(null==e)return!1;switch(e.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return!0}return!1}function r(e){return t(e)||null!=e&&"FunctionDeclaration"===e.type}function a(e){switch(e.type){case"IfStatement":return null!=e.alternate?e.alternate:e.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return e.body}return null}function o(e){var n;if("IfStatement"!==e.type)return!1;if(null==e.alternate)return!1;n=e.consequent;do{if("IfStatement"===n.type&&null==n.alternate)return!0;n=a(n)}while(n);return!1}n.exports={isExpression:e,isStatement:t,isIterationStatement:l,isSourceElement:r,isProblematicIfStatement:o,trailingStatement:a}}()},{}],177:[function(e,n){!function(){"use strict";function e(e){return e>=48&&57>=e}function l(n){return e(n)||n>=97&&102>=n||n>=65&&70>=n}function t(e){return e>=48&&55>=e}function r(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&i.indexOf(e)>=0}function a(e){return 10===e||13===e||8232===e||8233===e}function o(e){return e>=97&&122>=e||e>=65&&90>=e||36===e||95===e||92===e||e>=128&&s.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function u(e){return e>=97&&122>=e||e>=65&&90>=e||e>=48&&57>=e||36===e||95===e||92===e||e>=128&&s.NonAsciiIdentifierPart.test(String.fromCharCode(e))}var s,i;s={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")},i=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279],n.exports={isDecimalDigit:e,isHexDigit:l,isOctalDigit:t,isWhiteSpace:r,isLineTerminator:a,isIdentifierStart:o,isIdentifierPart:u}}()},{}],178:[function(e,n){!function(){"use strict";function l(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return!0;default:return!1}}function t(e,n){return n||"yield"!==e?r(e,n):!1}function r(e,n){if(n&&l(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function a(e,n){return"null"===e||"true"===e||"false"===e||t(e,n)}function o(e,n){return"null"===e||"true"===e||"false"===e||r(e,n)}function u(e){return"eval"===e||"arguments"===e}function s(e){var n,l,t;if(0===e.length)return!1;if(t=e.charCodeAt(0),!d.isIdentifierStart(t)||92===t)return!1;for(n=1,l=e.length;l>n;++n)if(t=e.charCodeAt(n),!d.isIdentifierPart(t)||92===t)return!1;return!0}function i(e,n){return s(e)&&!a(e,n)}function c(e,n){return s(e)&&!o(e,n)}var d=e("./code");n.exports={isKeywordES5:t,isKeywordES6:r,isReservedWordES5:a,isReservedWordES6:o,isRestrictedWord:u,isIdentifierName:s,isIdentifierES5:i,isIdentifierES6:c}}()},{"./code":177}],179:[function(e,n,l){!function(){"use strict";l.ast=e("./ast"),l.code=e("./code"),l.keyword=e("./keyword")}()},{"./ast":176,"./code":177,"./keyword":178}],180:[function(e,n){n.exports={builtin:{Array:!1,ArrayBuffer:!1,Boolean:!1,constructor:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Float32Array:!1,Float64Array:!1,Function:!1,hasOwnProperty:!1,Infinity:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,isFinite:!1,isNaN:!1,isPrototypeOf:!1,JSON:!1,Map:!1,Math:!1,NaN:!1,Number:!1,Object:!1,parseFloat:!1,parseInt:!1,Promise:!1,propertyIsEnumerable:!1,Proxy:!1,RangeError:!1,ReferenceError:!1,Reflect:!1,RegExp:!1,Set:!1,String:!1,Symbol:!1,SyntaxError:!1,System:!1,toLocaleString:!1,toString:!1,TypeError:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1,undefined:!1,URIError:!1,valueOf:!1,WeakMap:!1,WeakSet:!1},nonstandard:{escape:!1,unescape:!1},browser:{addEventListener:!1,alert:!1,applicationCache:!1,atob:!1,Audio:!1,AudioProcessingEvent:!1,BeforeUnloadEvent:!1,Blob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,CloseEvent:!1,Comment:!1,CompositionEvent:!1,confirm:!1,console:!1,crypto:!1,CSS:!1,CustomEvent:!1,DataView:!1,Debug:!1,defaultStatus:!1,devicePixelRatio:!1,dispatchEvent:!1,document:!1,Document:!1,DocumentFragment:!1,DOMParser:!1,DragEvent:!1,Element:!1,ElementTimeControl:!1,ErrorEvent:!1,event:!1,Event:!1,FileReader:!1,find:!1,focus:!1,FocusEvent:!1,FormData:!1,frameElement:!1,frames:!1,GamepadEvent:!1,getComputedStyle:!1,getSelection:!1,HashChangeEvent:!1,history:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,IDBCursor:!1,IDBCursorWithValue:!1,IDBDatabase:!1,IDBEnvironment:!1,IDBFactory:!1,IDBIndex:!1,IDBKeyRange:!1,IDBObjectStore:!1,IDBOpenDBRequest:!1,IDBRequest:!1,IDBTransaction:!1,IDBVersionChangeEvent:!1,Image:!1,indexedDB:!1,innerHeight:!1,innerWidth:!1,InputEvent:!1,Intl:!1,KeyboardEvent:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,navigator:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,OfflineAudioCompletionEvent:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,opera:!1,Option:!1,outerHeight:!1,outerWidth:!1,PageTransitionEvent:!1,pageXOffset:!1,pageYOffset:!1,parent:!1,PopStateEvent:!1,postMessage:!1,print:!1,ProgressEvent:!1,prompt:!1,Range:!1,removeEventListener:!1,requestAnimationFrame:!1,resizeBy:!1,resizeTo:!1,screen:!1,screenX:!1,screenY:!1,scroll:!1,scrollbars:!1,scrollBy:!1,scrollTo:!1,scrollX:!1,scrollY:!1,self:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,showModalDialog:!1,status:!1,stop:!1,StorageEvent:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimationElement:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCSSRule:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGEvent:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLinearGradientElement:!1,SVGLineElement:!1,SVGLocatable:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGMPathElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSVGElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformable:!1,SVGTransformList:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGUnitTypes:!1,SVGURIReference:!1,SVGUseElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGVKernElement:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,TouchEvent:!1,UIEvent:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,WheelEvent:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},worker:{importScripts:!0,postMessage:!0,self:!0},node:{__dirname:!1,__filename:!1,arguments:!1,Buffer:!1,clearImmediate:!1,clearInterval:!1,clearTimeout:!1,console:!1,DataView:!1,exports:!0,GLOBAL:!1,global:!1,module:!1,process:!1,require:!1,setImmediate:!1,setInterval:!1,setTimeout:!1},amd:{define:!1,require:!1},mocha:{after:!1,afterEach:!1,before:!1,beforeEach:!1,context:!1,describe:!1,it:!1,setup:!1,specify:!1,suite:!1,suiteSetup:!1,suiteTeardown:!1,teardown:!1,test:!1,xcontext:!1,xdescribe:!1,xit:!1,xspecify:!1},jasmine:{afterAll:!1,afterEach:!1,beforeAll:!1,beforeEach:!1,describe:!1,expect:!1,fail:!1,fdescribe:!1,fit:!1,it:!1,jasmine:!1,pending:!1,runs:!1,spyOn:!1,waits:!1,waitsFor:!1,xdescribe:!1,xit:!1},qunit:{asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,"throws":!1},phantomjs:{console:!0,exports:!0,phantom:!0,require:!0,WebPage:!0},couch:{emit:!1,exports:!1,getRow:!1,log:!1,module:!1,provides:!1,require:!1,respond:!1,send:!1,start:!1,sum:!1},rhino:{defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},wsh:{ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WScript:!0,WSH:!0,XDomainRequest:!0},jquery:{$:!1,jQuery:!1},yui:{Y:!1,YUI:!1,YUI_config:!1},shelljs:{cat:!1,cd:!1,chmod:!1,config:!1,cp:!1,dirs:!1,echo:!1,env:!1,error:!1,exec:!1,exit:!1,find:!1,grep:!1,ls:!1,mkdir:!1,mv:!1,popd:!1,pushd:!1,pwd:!1,rm:!1,sed:!1,target:!1,tempdir:!1,test:!1,which:!1},prototypejs:{$:!1,$$:!1,$A:!1,$break:!1,$continue:!1,$F:!1,$H:!1,$R:!1,$w:!1,Abstract:!1,Ajax:!1,Autocompleter:!1,Builder:!1,Class:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Element:!1,Enumerable:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Scriptaculous:!1,Selector:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Template:!1,Toggle:!1,Try:!1},meteor:{$:!1,_:!1,Accounts:!1,App:!1,Assets:!1,Blaze:!1,check:!1,Cordova:!1,DDP:!1,DDPServer:!1,Deps:!1,EJSON:!1,Email:!1,HTTP:!1,Log:!1,Match:!1,Meteor:!1,Mongo:!1,MongoInternals:!1,Npm:!1,Package:!1,Plugin:!1,process:!1,Random:!1,ReactiveDict:!1,ReactiveVar:!1,Router:!1,Session:!1,share:!1,Spacebars:!1,Template:!1,Tinytest:!1,Tracker:!1,UI:!1,Utils:!1,WebApp:!1,WebAppInternals:!1},mongo:{_isWindows:!1,_rand:!1,BulkWriteResult:!1,cat:!1,cd:!1,connect:!1,db:!1,getHostName:!1,getMemInfo:!1,hostname:!1,listFiles:!1,load:!1,ls:!1,md5sumFile:!1,mkdir:!1,Mongo:!1,ObjectId:!1,PlanCache:!1,pwd:!1,quit:!1,removeFile:!1,rs:!1,sh:!1,UUID:!1,version:!1,WriteResult:!1}}},{}],181:[function(e,n){n.exports=e("./globals.json")},{"./globals.json":180}],182:[function(e,n){var l=e("is-nan"),t=e("is-finite");n.exports=Number.isInteger||function(e){return"number"==typeof e&&!l(e)&&t(e)&&parseInt(e,10)===e}},{"is-finite":183,"is-nan":184}],183:[function(e,n){"use strict";n.exports=Number.isFinite||function(e){return"number"!=typeof e||e!==e||1/0===e||e===-1/0?!1:!0}},{}],184:[function(e,n){"use strict";n.exports=function(e){return e!==e}},{}],185:[function(e,n){function l(){return new RegExp("("+[].slice.call(arguments).map(function(e){var e=e.toString();return"(?:"+e.substring(1,e.length-1)+")"}).join("|")+")")}function t(e){var n=e.toString();return new RegExp("^"+n.substring(1,n.length-1)+"$")}var r={string1:/"(?:(?:\\\n|\\"|[^"\n]))*?"/,string2:/'(?:(?:\\\n|\\'|[^'\n]))*?'/,comment1:/\/\*[\s\S]*?\*\//,comment2:/\/\/.*?\n/,whitespace:/\s+/,keyword:/\b(?:var|let|for|if|else|in|class|function|return|with|case|break|switch|export|new|while|do|throw|catch)\b/,regexp:/\/(?:(?:\\\/|[^\n\/]))*?\//,name:/[a-zA-Z_\$][a-zA-Z_\$0-9]*/,number:/\d+(?:\.\d+)?(?:e[+-]?\d+)?/,parens:/[\(\)]/,curly:/[{}]/,square:/[\[\]]/,punct:/[;.:\?\^%<>=!&|+\-,~]/},a=l(r.string1,r.string2,r.comment1,r.comment2,r.regexp,r.whitespace,r.name,r.number,r.parens,r.curly,r.square,r.punct),o={};for(var u in r)o[u]=t(r[u]);n.exports=function(e,n){return e.split(a).filter(function(e,l){if(l%2)return!0;if(""!==e){if(!n)throw new Error("invalid token:"+JSON.stringify(e));return!0}})},n.exports.type=function(e){for(var n in r)if(o[n].test(e))return n;return"invalid"}},{}],186:[function(e,n){var l=[],t=[];n.exports=function(e,n){if(e===n)return 0;var r=e.length,a=n.length;if(0===r)return a;if(0===a)return r;for(var o,u,s,i,c=0,d=0;r>c;)t[c]=e.charCodeAt(c),l[c]=++c;for(;a>d;)for(o=n.charCodeAt(d),s=d++,u=d,c=0;r>c;c++)i=o===t[c]?s:s+1,s=l[c],u=l[c]=s>u?i>u?u+1:i:i>s?s+1:i;return u}},{}],187:[function(e,n){function l(e){for(var n=-1,l=e?e.length:0,t=-1,r=[];++n<l;){var a=e[n];a&&(r[++t]=a)}return r}n.exports=l},{}],188:[function(e,n){function l(e,n,l){var a=e?e.length:0;return l&&r(e,n,l)&&(n=!1),a?t(e,n):[]}var t=e("../internal/baseFlatten"),r=e("../internal/isIterateeCall");n.exports=l},{"../internal/baseFlatten":215,"../internal/isIterateeCall":252}],189:[function(e,n){function l(e){var n=e?e.length:0;return n?e[n-1]:void 0}n.exports=l},{}],190:[function(e,n){function l(){var e=arguments[0];if(!e||!e.length)return e;for(var n=0,l=t,r=arguments.length;++n<r;)for(var o=0,u=arguments[n];(o=l(e,u,o))>-1;)a.call(e,o,1);return e}var t=e("../internal/baseIndexOf"),r=Array.prototype,a=r.splice;n.exports=l},{"../internal/baseIndexOf":220}],191:[function(e,n){function l(e,n,l,u){var s=e?e.length:0;return s?("boolean"!=typeof n&&null!=n&&(u=l,l=a(e,n,u)?null:n,n=!1),l=null==l?l:t(l,u,3),n?o(e,l):r(e,l)):[]}var t=e("../internal/baseCallback"),r=e("../internal/baseUniq"),a=e("../internal/isIterateeCall"),o=e("../internal/sortedUniq");n.exports=l},{"../internal/baseCallback":209,"../internal/baseUniq":233,"../internal/isIterateeCall":252,"../internal/sortedUniq":258}],192:[function(e,n){n.exports=e("./includes")},{"./includes":196}],193:[function(e,n){n.exports=e("./forEach")},{"./forEach":194}],194:[function(e,n){function l(e,n,l){return"function"==typeof n&&"undefined"==typeof l&&o(e)?t(e,n):r(e,a(n,l,3))}var t=e("../internal/arrayEach"),r=e("../internal/baseEach"),a=e("../internal/bindCallback"),o=e("../lang/isArray");n.exports=l},{"../internal/arrayEach":203,"../internal/baseEach":213,"../internal/bindCallback":235,"../lang/isArray":263}],195:[function(e,n){var l=e("../internal/createAggregator"),t=Object.prototype,r=t.hasOwnProperty,a=l(function(e,n,l){r.call(e,l)?e[l].push(n):e[l]=[n]});n.exports=a},{"../internal/createAggregator":240}],196:[function(e,n){function l(e,n,l){var i=e?e.length:0;return a(i)||(e=u(e),i=e.length),i?(l="number"==typeof l?0>l?s(i+l,0):l||0:0,"string"==typeof e||!r(e)&&o(e)?i>l&&e.indexOf(n,l)>-1:t(e,n,l)>-1):!1}var t=e("../internal/baseIndexOf"),r=e("../lang/isArray"),a=e("../internal/isLength"),o=e("../lang/isString"),u=e("../object/values"),s=Math.max;n.exports=l},{"../internal/baseIndexOf":220,"../internal/isLength":253,"../lang/isArray":263,"../lang/isString":271,"../object/values":279}],197:[function(e,n){function l(e,n,l){var u=o(e)?t:a;return n=r(n,l,3),u(e,n)}var t=e("../internal/arrayMap"),r=e("../internal/baseCallback"),a=e("../internal/baseMap"),o=e("../lang/isArray");n.exports=l},{"../internal/arrayMap":204,"../internal/baseCallback":209,"../internal/baseMap":224,"../lang/isArray":263}],198:[function(e,n){function l(e,n,l,s){var i=u(e)?t:o;return i(e,r(n,s,4),l,arguments.length<3,a)}var t=e("../internal/arrayReduceRight"),r=e("../internal/baseCallback"),a=e("../internal/baseEachRight"),o=e("../internal/baseReduce"),u=e("../lang/isArray");n.exports=l},{"../internal/arrayReduceRight":205,"../internal/baseCallback":209,"../internal/baseEachRight":214,"../internal/baseReduce":228,"../lang/isArray":263}],199:[function(e,n){function l(e,n,l){var u=o(e)?t:a;return("function"!=typeof n||"undefined"!=typeof l)&&(n=r(n,l,3)),u(e,n)}var t=e("../internal/arraySome"),r=e("../internal/baseCallback"),a=e("../internal/baseSome"),o=e("../lang/isArray");n.exports=l},{"../internal/arraySome":206,"../internal/baseCallback":209,"../internal/baseSome":230,"../lang/isArray":263}],200:[function(e,n){function l(e,n,l){var i=-1,c=e?e.length:0,d=s(c)?Array(c):[];return l&&u(e,n,l)&&(n=null),n=t(n,l,3),r(e,function(e,l,t){d[++i]={criteria:n(e,l,t),index:i,value:e}}),a(d,o)}var t=e("../internal/baseCallback"),r=e("../internal/baseEach"),a=e("../internal/baseSortBy"),o=e("../internal/compareAscending"),u=e("../internal/isIterateeCall"),s=e("../internal/isLength");n.exports=l},{"../internal/baseCallback":209,"../internal/baseEach":213,"../internal/baseSortBy":231,"../internal/compareAscending":239,"../internal/isIterateeCall":252,"../internal/isLength":253}],201:[function(e,n){(function(l){function t(e){var n=e?e.length:0;for(this.data={hash:u(null),set:new o};n--;)this.push(e[n])}var r=e("./cachePush"),a=e("../lang/isNative"),o=a(o=l.Set)&&o,u=a(u=Object.create)&&u;t.prototype.push=r,n.exports=t}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":267,"./cachePush":238}],202:[function(e,n){function l(e,n){var l=-1,t=e.length;for(n||(n=Array(t));++l<t;)n[l]=e[l];return n}n.exports=l},{}],203:[function(e,n){function l(e,n){for(var l=-1,t=e.length;++l<t&&n(e[l],l,e)!==!1;);return e}n.exports=l},{}],204:[function(e,n){function l(e,n){for(var l=-1,t=e.length,r=Array(t);++l<t;)r[l]=n(e[l],l,e);return r}n.exports=l},{}],205:[function(e,n){function l(e,n,l,t){var r=e.length;for(t&&r&&(l=e[--r]);r--;)l=n(l,e[r],r,e);return l}n.exports=l},{}],206:[function(e,n){function l(e,n){for(var l=-1,t=e.length;++l<t;)if(n(e[l],l,e))return!0;return!1}n.exports=l},{}],207:[function(e,n){function l(e,n){return"undefined"==typeof e?n:e}n.exports=l},{}],208:[function(e,n){function l(e,n,l){var a=r(n);if(!l)return t(n,e,a);for(var o=-1,u=a.length;++o<u;){var s=a[o],i=e[s],c=l(i,n[s],s,e,n);(c===c?c===i:i!==i)&&("undefined"!=typeof i||s in e)||(e[s]=c)}return e}var t=e("./baseCopy"),r=e("../object/keys");n.exports=l},{"../object/keys":277,"./baseCopy":212}],209:[function(e,n){function l(e,n,l){var i=typeof e;return"function"==i?"undefined"!=typeof n&&s(e)?o(e,n,l):e:null==e?u:"object"==i?t(e):"undefined"==typeof n?a(e+""):r(e+"",n)}var t=e("./baseMatches"),r=e("./baseMatchesProperty"),a=e("./baseProperty"),o=e("./bindCallback"),u=e("../utility/identity"),s=e("./isBindable");n.exports=l},{"../utility/identity":283,"./baseMatches":225,"./baseMatchesProperty":226,"./baseProperty":227,"./bindCallback":235,"./isBindable":250}],210:[function(e,n){function l(e,n,g,h,m,y,b){var _;if(g&&(_=m?g(e,h,m):g(e)),"undefined"!=typeof _)return _;if(!d(e))return e;var I=c(e);if(I){if(_=u(e),!n)return t(e,_)}else{var E=B.call(e),k=E==x;if(E!=v&&E!=f&&(!k||m))return D[E]?s(e,E,n):m?e:{};if(_=i(k?{}:e),!n)return a(e,_,p(e))}y||(y=[]),b||(b=[]);for(var w=y.length;w--;)if(y[w]==e)return b[w];return y.push(e),b.push(_),(I?r:o)(e,function(t,r){_[r]=l(t,n,g,r,e,y,b)}),_}var t=e("./arrayCopy"),r=e("./arrayEach"),a=e("./baseCopy"),o=e("./baseForOwn"),u=e("./initCloneArray"),s=e("./initCloneByTag"),i=e("./initCloneObject"),c=e("../lang/isArray"),d=e("../lang/isObject"),p=e("../object/keys"),f="[object Arguments]",g="[object Array]",h="[object Boolean]",m="[object Date]",y="[object Error]",x="[object Function]",b="[object Map]",_="[object Number]",v="[object Object]",I="[object RegExp]",E="[object Set]",k="[object String]",w="[object WeakMap]",R="[object ArrayBuffer]",S="[object Float32Array]",C="[object Float64Array]",A="[object Int8Array]",j="[object Int16Array]",T="[object Int32Array]",L="[object Uint8Array]",P="[object Uint8ClampedArray]",O="[object Uint16Array]",M="[object Uint32Array]",D={};D[f]=D[g]=D[R]=D[h]=D[m]=D[S]=D[C]=D[A]=D[j]=D[T]=D[_]=D[v]=D[I]=D[k]=D[L]=D[P]=D[O]=D[M]=!0,D[y]=D[x]=D[b]=D[E]=D[w]=!1;var N=Object.prototype,B=N.toString;n.exports=l},{"../lang/isArray":263,"../lang/isObject":269,"../object/keys":277,"./arrayCopy":202,"./arrayEach":203,"./baseCopy":212,"./baseForOwn":217,"./initCloneArray":247,"./initCloneByTag":248,"./initCloneObject":249}],211:[function(e,n){function l(e,n){if(e!==n){var l=e===e,t=n===n;if(e>n||!l||"undefined"==typeof e&&t)return 1;if(n>e||!t||"undefined"==typeof n&&l)return-1}return 0}n.exports=l},{}],212:[function(e,n){function l(e,n,l){l||(l=n,n={});for(var t=-1,r=l.length;++t<r;){var a=l[t];n[a]=e[a]}return n}n.exports=l},{}],213:[function(e,n){function l(e,n){var l=e?e.length:0;if(!r(l))return t(e,n);for(var o=-1,u=a(e);++o<l&&n(u[o],o,u)!==!1;);return e}var t=e("./baseForOwn"),r=e("./isLength"),a=e("./toObject");n.exports=l},{"./baseForOwn":217,"./isLength":253,"./toObject":259}],214:[function(e,n){function l(e,n){var l=e?e.length:0;if(!r(l))return t(e,n);for(var o=a(e);l--&&n(o[l],l,o)!==!1;);return e}var t=e("./baseForOwnRight"),r=e("./isLength"),a=e("./toObject");n.exports=l},{"./baseForOwnRight":218,"./isLength":253,"./toObject":259}],215:[function(e,n){function l(e,n,u,s){for(var i=(s||0)-1,c=e.length,d=-1,p=[];++i<c;){var f=e[i];if(o(f)&&a(f.length)&&(r(f)||t(f))){n&&(f=l(f,n,u));var g=-1,h=f.length;for(p.length+=h;++g<h;)p[++d]=f[g]}else u||(p[++d]=f)}return p}var t=e("../lang/isArguments"),r=e("../lang/isArray"),a=e("./isLength"),o=e("./isObjectLike");n.exports=l},{"../lang/isArguments":262,"../lang/isArray":263,"./isLength":253,"./isObjectLike":254}],216:[function(e,n){function l(e,n,l){for(var r=-1,a=t(e),o=l(e),u=o.length;++r<u;){var s=o[r];if(n(a[s],s,a)===!1)break}return e}var t=e("./toObject");n.exports=l},{"./toObject":259}],217:[function(e,n){function l(e,n){return t(e,n,r)}var t=e("./baseFor"),r=e("../object/keys");n.exports=l},{"../object/keys":277,"./baseFor":216}],218:[function(e,n){function l(e,n){return t(e,n,r)}var t=e("./baseForRight"),r=e("../object/keys");n.exports=l},{"../object/keys":277,"./baseForRight":219}],219:[function(e,n){function l(e,n,l){for(var r=t(e),a=l(e),o=a.length;o--;){var u=a[o];if(n(r[u],u,r)===!1)break}return e}var t=e("./toObject");n.exports=l},{"./toObject":259}],220:[function(e,n){function l(e,n,l){if(n!==n)return t(e,l);for(var r=(l||0)-1,a=e.length;++r<a;)if(e[r]===n)return r;return-1}var t=e("./indexOfNaN");n.exports=l},{"./indexOfNaN":246}],221:[function(e,n){function l(e,n,r,a,o,u){if(e===n)return 0!==e||1/e==1/n;
var s=typeof e,i=typeof n;return"function"!=s&&"object"!=s&&"function"!=i&&"object"!=i||null==e||null==n?e!==e&&n!==n:t(e,n,l,r,a,o,u)}var t=e("./baseIsEqualDeep");n.exports=l},{"./baseIsEqualDeep":222}],222:[function(e,n){function l(e,n,l,d,g,h,m){var y=o(e),x=o(n),b=i,_=i;y||(b=f.call(e),b==s?b=c:b!=c&&(y=u(e))),x||(_=f.call(n),_==s?_=c:_!=c&&(x=u(n)));var v=b==c,I=_==c,E=b==_;if(E&&!y&&!v)return r(e,n,b);var k=v&&p.call(e,"__wrapped__"),w=I&&p.call(n,"__wrapped__");if(k||w)return l(k?e.value():e,w?n.value():n,d,g,h,m);if(!E)return!1;h||(h=[]),m||(m=[]);for(var R=h.length;R--;)if(h[R]==e)return m[R]==n;h.push(e),m.push(n);var S=(y?t:a)(e,n,l,d,g,h,m);return h.pop(),m.pop(),S}var t=e("./equalArrays"),r=e("./equalByTag"),a=e("./equalObjects"),o=e("../lang/isArray"),u=e("../lang/isTypedArray"),s="[object Arguments]",i="[object Array]",c="[object Object]",d=Object.prototype,p=d.hasOwnProperty,f=d.toString;n.exports=l},{"../lang/isArray":263,"../lang/isTypedArray":272,"./equalArrays":243,"./equalByTag":244,"./equalObjects":245}],223:[function(e,n){function l(e,n,l,r,o){var u=n.length;if(null==e)return!u;for(var s=-1,i=!o;++s<u;)if(i&&r[s]?l[s]!==e[n[s]]:!a.call(e,n[s]))return!1;for(s=-1;++s<u;){var c=n[s];if(i&&r[s])var d=a.call(e,c);else{var p=e[c],f=l[s];d=o?o(p,f,c):void 0,"undefined"==typeof d&&(d=t(f,p,o,!0))}if(!d)return!1}return!0}var t=e("./baseIsEqual"),r=Object.prototype,a=r.hasOwnProperty;n.exports=l},{"./baseIsEqual":221}],224:[function(e,n){function l(e,n){var l=[];return t(e,function(e,t,r){l.push(n(e,t,r))}),l}var t=e("./baseEach");n.exports=l},{"./baseEach":213}],225:[function(e,n){function l(e){var n=a(e),l=n.length;if(1==l){var o=n[0],s=e[o];if(r(s))return function(e){return null!=e&&s===e[o]&&u.call(e,o)}}for(var i=Array(l),c=Array(l);l--;)s=e[n[l]],i[l]=s,c[l]=r(s);return function(e){return t(e,n,i,c)}}var t=e("./baseIsMatch"),r=e("./isStrictComparable"),a=e("../object/keys"),o=Object.prototype,u=o.hasOwnProperty;n.exports=l},{"../object/keys":277,"./baseIsMatch":223,"./isStrictComparable":255}],226:[function(e,n){function l(e,n){return r(n)?function(l){return null!=l&&l[e]===n}:function(l){return null!=l&&t(n,l[e],null,!0)}}var t=e("./baseIsEqual"),r=e("./isStrictComparable");n.exports=l},{"./baseIsEqual":221,"./isStrictComparable":255}],227:[function(e,n){function l(e){return function(n){return null==n?void 0:n[e]}}n.exports=l},{}],228:[function(e,n){function l(e,n,l,t,r){return r(e,function(e,r,a){l=t?(t=!1,e):n(l,e,r,a)}),l}n.exports=l},{}],229:[function(e,n){var l=e("../utility/identity"),t=e("./metaMap"),r=t?function(e,n){return t.set(e,n),e}:l;n.exports=r},{"../utility/identity":283,"./metaMap":256}],230:[function(e,n){function l(e,n){var l;return t(e,function(e,t,r){return l=n(e,t,r),!l}),!!l}var t=e("./baseEach");n.exports=l},{"./baseEach":213}],231:[function(e,n){function l(e,n){var l=e.length;for(e.sort(n);l--;)e[l]=e[l].value;return e}n.exports=l},{}],232:[function(e,n){function l(e){return"string"==typeof e?e:null==e?"":e+""}n.exports=l},{}],233:[function(e,n){function l(e,n){var l=-1,o=t,u=e.length,s=!0,i=s&&u>=200,c=i&&a(),d=[];c?(o=r,s=!1):(i=!1,c=n?[]:d);e:for(;++l<u;){var p=e[l],f=n?n(p,l,e):p;if(s&&p===p){for(var g=c.length;g--;)if(c[g]===f)continue e;n&&c.push(f),d.push(p)}else o(c,f)<0&&((n||i)&&c.push(f),d.push(p))}return d}var t=e("./baseIndexOf"),r=e("./cacheIndexOf"),a=e("./createCache");n.exports=l},{"./baseIndexOf":220,"./cacheIndexOf":237,"./createCache":242}],234:[function(e,n){function l(e,n){for(var l=-1,t=n.length,r=Array(t);++l<t;)r[l]=e[n[l]];return r}n.exports=l},{}],235:[function(e,n){function l(e,n,l){if("function"!=typeof e)return t;if("undefined"==typeof n)return e;switch(l){case 1:return function(l){return e.call(n,l)};case 3:return function(l,t,r){return e.call(n,l,t,r)};case 4:return function(l,t,r,a){return e.call(n,l,t,r,a)};case 5:return function(l,t,r,a,o){return e.call(n,l,t,r,a,o)}}return function(){return e.apply(n,arguments)}}var t=e("../utility/identity");n.exports=l},{"../utility/identity":283}],236:[function(e,n){(function(l){function t(e){return u.call(e,0)}var r=e("../utility/constant"),a=e("../lang/isNative"),o=a(o=l.ArrayBuffer)&&o,u=a(u=o&&new o(0).slice)&&u,s=Math.floor,i=a(i=l.Uint8Array)&&i,c=function(){try{var e=a(e=l.Float64Array)&&e,n=new e(new o(10),0,1)&&e}catch(t){}return n}(),d=c?c.BYTES_PER_ELEMENT:0;u||(t=o&&i?function(e){var n=e.byteLength,l=c?s(n/d):0,t=l*d,r=new o(n);if(l){var a=new c(r,0,l);a.set(new c(e,0,l))}return n!=t&&(a=new i(r,t),a.set(new i(e,t))),r}:r(null)),n.exports=t}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":267,"../utility/constant":282}],237:[function(e,n){function l(e,n){var l=e.data,r="string"==typeof n||t(n)?l.set.has(n):l.hash[n];return r?0:-1}var t=e("../lang/isObject");n.exports=l},{"../lang/isObject":269}],238:[function(e,n){function l(e){var n=this.data;"string"==typeof e||t(e)?n.set.add(e):n.hash[e]=!0}var t=e("../lang/isObject");n.exports=l},{"../lang/isObject":269}],239:[function(e,n){function l(e,n){return t(e.criteria,n.criteria)||e.index-n.index}var t=e("./baseCompareAscending");n.exports=l},{"./baseCompareAscending":211}],240:[function(e,n){function l(e,n){return function(l,o,u){var s=n?n():{};if(o=t(o,u,3),a(l))for(var i=-1,c=l.length;++i<c;){var d=l[i];e(s,d,o(d,i,l),l)}else r(l,function(n,l,t){e(s,n,o(n,l,t),t)});return s}}var t=e("./baseCallback"),r=e("./baseEach"),a=e("../lang/isArray");n.exports=l},{"../lang/isArray":263,"./baseCallback":209,"./baseEach":213}],241:[function(e,n){function l(e){return function(){var n=arguments.length,l=arguments[0];if(2>n||null==l)return l;if(n>3&&r(arguments[1],arguments[2],arguments[3])&&(n=2),n>3&&"function"==typeof arguments[n-2])var a=t(arguments[--n-1],arguments[n--],5);else n>2&&"function"==typeof arguments[n-1]&&(a=arguments[--n]);for(var o=0;++o<n;){var u=arguments[o];u&&e(l,u,a)}return l}}var t=e("./bindCallback"),r=e("./isIterateeCall");n.exports=l},{"./bindCallback":235,"./isIterateeCall":252}],242:[function(e,n){(function(l){var t=e("./SetCache"),r=e("../utility/constant"),a=e("../lang/isNative"),o=a(o=l.Set)&&o,u=a(u=Object.create)&&u,s=u&&o?function(e){return new t(e)}:r(null);n.exports=s}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":267,"../utility/constant":282,"./SetCache":201}],243:[function(e,n){function l(e,n,l,t,r,a,o){var u=-1,s=e.length,i=n.length,c=!0;if(s!=i&&!(r&&i>s))return!1;for(;c&&++u<s;){var d=e[u],p=n[u];if(c=void 0,t&&(c=r?t(p,d,u):t(d,p,u)),"undefined"==typeof c)if(r)for(var f=i;f--&&(p=n[f],!(c=d&&d===p||l(d,p,t,r,a,o))););else c=d&&d===p||l(d,p,t,r,a,o)}return!!c}n.exports=l},{}],244:[function(e,n){function l(e,n,l){switch(l){case t:case r:return+e==+n;case a:return e.name==n.name&&e.message==n.message;case o:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case u:case s:return e==n+""}return!1}var t="[object Boolean]",r="[object Date]",a="[object Error]",o="[object Number]",u="[object RegExp]",s="[object String]";n.exports=l},{}],245:[function(e,n){function l(e,n,l,r,o,u,s){var i=t(e),c=i.length,d=t(n),p=d.length;if(c!=p&&!o)return!1;for(var f,g=-1;++g<c;){var h=i[g],m=a.call(n,h);if(m){var y=e[h],x=n[h];m=void 0,r&&(m=o?r(x,y,h):r(y,x,h)),"undefined"==typeof m&&(m=y&&y===x||l(y,x,r,o,u,s))}if(!m)return!1;f||(f="constructor"==h)}if(!f){var b=e.constructor,_=n.constructor;if(b!=_&&"constructor"in e&&"constructor"in n&&!("function"==typeof b&&b instanceof b&&"function"==typeof _&&_ instanceof _))return!1}return!0}var t=e("../object/keys"),r=Object.prototype,a=r.hasOwnProperty;n.exports=l},{"../object/keys":277}],246:[function(e,n){function l(e,n,l){for(var t=e.length,r=l?n||t:(n||0)-1;l?r--:++r<t;){var a=e[r];if(a!==a)return r}return-1}n.exports=l},{}],247:[function(e,n){function l(e){var n=e.length,l=new e.constructor(n);return n&&"string"==typeof e[0]&&r.call(e,"index")&&(l.index=e.index,l.input=e.input),l}var t=Object.prototype,r=t.hasOwnProperty;n.exports=l},{}],248:[function(e,n){function l(e,n,l){var _=e.constructor;switch(n){case i:return t(e);case r:case a:return new _(+e);case c:case d:case p:case f:case g:case h:case m:case y:case x:var v=e.buffer;return new _(l?t(v):v,e.byteOffset,e.length);case o:case s:return new _(e);case u:var I=new _(e.source,b.exec(e));I.lastIndex=e.lastIndex}return I}var t=e("./bufferClone"),r="[object Boolean]",a="[object Date]",o="[object Number]",u="[object RegExp]",s="[object String]",i="[object ArrayBuffer]",c="[object Float32Array]",d="[object Float64Array]",p="[object Int8Array]",f="[object Int16Array]",g="[object Int32Array]",h="[object Uint8Array]",m="[object Uint8ClampedArray]",y="[object Uint16Array]",x="[object Uint32Array]",b=/\w*$/;n.exports=l},{"./bufferClone":236}],249:[function(e,n){function l(e){var n=e.constructor;return"function"==typeof n&&n instanceof n||(n=Object),new n}n.exports=l},{}],250:[function(e,n){function l(e){var n=!(a.funcNames?e.name:a.funcDecomp);if(!n){var l=s.call(e);a.funcNames||(n=!o.test(l)),n||(n=u.test(l)||r(e),t(e,n))}return n}var t=e("./baseSetData"),r=e("../lang/isNative"),a=e("../support"),o=/^\s*function[ \n\r\t]+\w/,u=/\bthis\b/,s=Function.prototype.toString;n.exports=l},{"../lang/isNative":267,"../support":281,"./baseSetData":229}],251:[function(e,n){function l(e,n){return e=+e,n=null==n?t:n,e>-1&&e%1==0&&n>e}var t=Math.pow(2,53)-1;n.exports=l},{}],252:[function(e,n){function l(e,n,l){if(!a(l))return!1;var o=typeof n;if("number"==o)var u=l.length,s=r(u)&&t(n,u);else s="string"==o&&n in l;return s&&l[n]===e}var t=e("./isIndex"),r=e("./isLength"),a=e("../lang/isObject");n.exports=l},{"../lang/isObject":269,"./isIndex":251,"./isLength":253}],253:[function(e,n){function l(e){return"number"==typeof e&&e>-1&&e%1==0&&t>=e}var t=Math.pow(2,53)-1;n.exports=l},{}],254:[function(e,n){function l(e){return e&&"object"==typeof e||!1}n.exports=l},{}],255:[function(e,n){function l(e){return e===e&&(0===e?1/e>0:!t(e))}var t=e("../lang/isObject");n.exports=l},{"../lang/isObject":269}],256:[function(e,n){(function(l){var t=e("../lang/isNative"),r=t(r=l.WeakMap)&&r,a=r&&new r;n.exports=a}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":267}],257:[function(e,n){function l(e){for(var n=u(e),l=n.length,i=l&&e.length,d=i&&o(i)&&(r(e)||s.nonEnumArgs&&t(e)),p=-1,f=[];++p<l;){var g=n[p];(d&&a(g,i)||c.call(e,g))&&f.push(g)}return f}var t=e("../lang/isArguments"),r=e("../lang/isArray"),a=e("./isIndex"),o=e("./isLength"),u=e("../object/keysIn"),s=e("../support"),i=Object.prototype,c=i.hasOwnProperty;n.exports=l},{"../lang/isArguments":262,"../lang/isArray":263,"../object/keysIn":278,"../support":281,"./isIndex":251,"./isLength":253}],258:[function(e,n){function l(e,n){for(var l,t=-1,r=e.length,a=-1,o=[];++t<r;){var u=e[t],s=n?n(u,t,e):u;t&&l===s||(l=s,o[++a]=u)}return o}n.exports=l},{}],259:[function(e,n){function l(e){return t(e)?e:Object(e)}var t=e("../lang/isObject");n.exports=l},{"../lang/isObject":269}],260:[function(e,n){function l(e,n,l,o){return"boolean"!=typeof n&&null!=n&&(o=l,l=a(e,n,o)?null:n,n=!1),l="function"==typeof l&&r(l,o,1),t(e,n,l)}var t=e("../internal/baseClone"),r=e("../internal/bindCallback"),a=e("../internal/isIterateeCall");n.exports=l},{"../internal/baseClone":210,"../internal/bindCallback":235,"../internal/isIterateeCall":252}],261:[function(e,n){function l(e,n,l){return n="function"==typeof n&&r(n,l,1),t(e,!0,n)}var t=e("../internal/baseClone"),r=e("../internal/bindCallback");n.exports=l},{"../internal/baseClone":210,"../internal/bindCallback":235}],262:[function(e,n){function l(e){var n=r(e)?e.length:void 0;return t(n)&&u.call(e)==a||!1}var t=e("../internal/isLength"),r=e("../internal/isObjectLike"),a="[object Arguments]",o=Object.prototype,u=o.toString;n.exports=l},{"../internal/isLength":253,"../internal/isObjectLike":254}],263:[function(e,n){var l=e("../internal/isLength"),t=e("./isNative"),r=e("../internal/isObjectLike"),a="[object Array]",o=Object.prototype,u=o.toString,s=t(s=Array.isArray)&&s,i=s||function(e){return r(e)&&l(e.length)&&u.call(e)==a||!1};n.exports=i},{"../internal/isLength":253,"../internal/isObjectLike":254,"./isNative":267}],264:[function(e,n){function l(e){return e===!0||e===!1||t(e)&&o.call(e)==r||!1}var t=e("../internal/isObjectLike"),r="[object Boolean]",a=Object.prototype,o=a.toString;n.exports=l},{"../internal/isObjectLike":254}],265:[function(e,n){function l(e){if(null==e)return!0;var n=e.length;return o(n)&&(r(e)||s(e)||t(e)||u(e)&&a(e.splice))?!n:!i(e).length}var t=e("./isArguments"),r=e("./isArray"),a=e("./isFunction"),o=e("../internal/isLength"),u=e("../internal/isObjectLike"),s=e("./isString"),i=e("../object/keys");n.exports=l},{"../internal/isLength":253,"../internal/isObjectLike":254,"../object/keys":277,"./isArguments":262,"./isArray":263,"./isFunction":266,"./isString":271}],266:[function(e,n){(function(l){function t(e){return"function"==typeof e||!1}var r=e("./isNative"),a="[object Function]",o=Object.prototype,u=o.toString,s=r(s=l.Uint8Array)&&s;(t(/x/)||s&&!t(s))&&(t=function(e){return u.call(e)==a}),n.exports=t}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./isNative":267}],267:[function(e,n){function l(e){return null==e?!1:i.call(e)==a?c.test(s.call(e)):r(e)&&o.test(e)||!1}var t=e("../string/escapeRegExp"),r=e("../internal/isObjectLike"),a="[object Function]",o=/^\[object .+?Constructor\]$/,u=Object.prototype,s=Function.prototype.toString,i=u.toString,c=RegExp("^"+t(i).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");n.exports=l},{"../internal/isObjectLike":254,"../string/escapeRegExp":280}],268:[function(e,n){function l(e){return"number"==typeof e||t(e)&&o.call(e)==r||!1}var t=e("../internal/isObjectLike"),r="[object Number]",a=Object.prototype,o=a.toString;n.exports=l},{"../internal/isObjectLike":254}],269:[function(e,n){function l(e){var n=typeof e;return"function"==n||e&&"object"==n||!1}n.exports=l},{}],270:[function(e,n){function l(e){return t(e)&&o.call(e)==r||!1}var t=e("../internal/isObjectLike"),r="[object RegExp]",a=Object.prototype,o=a.toString;n.exports=l},{"../internal/isObjectLike":254}],271:[function(e,n){function l(e){return"string"==typeof e||t(e)&&o.call(e)==r||!1}var t=e("../internal/isObjectLike"),r="[object String]",a=Object.prototype,o=a.toString;n.exports=l},{"../internal/isObjectLike":254}],272:[function(e,n){function l(e){return r(e)&&t(e.length)&&C[j.call(e)]||!1}var t=e("../internal/isLength"),r=e("../internal/isObjectLike"),a="[object Arguments]",o="[object Array]",u="[object Boolean]",s="[object Date]",i="[object Error]",c="[object Function]",d="[object Map]",p="[object Number]",f="[object Object]",g="[object RegExp]",h="[object Set]",m="[object String]",y="[object WeakMap]",x="[object ArrayBuffer]",b="[object Float32Array]",_="[object Float64Array]",v="[object Int8Array]",I="[object Int16Array]",E="[object Int32Array]",k="[object Uint8Array]",w="[object Uint8ClampedArray]",R="[object Uint16Array]",S="[object Uint32Array]",C={};C[b]=C[_]=C[v]=C[I]=C[E]=C[k]=C[w]=C[R]=C[S]=!0,C[a]=C[o]=C[x]=C[u]=C[s]=C[i]=C[c]=C[d]=C[p]=C[f]=C[g]=C[h]=C[m]=C[y]=!1;var A=Object.prototype,j=A.toString;n.exports=l},{"../internal/isLength":253,"../internal/isObjectLike":254}],273:[function(e,n){var l=e("../internal/baseAssign"),t=e("../internal/createAssigner"),r=t(l);n.exports=r},{"../internal/baseAssign":208,"../internal/createAssigner":241}],274:[function(e,n){function l(e){if(null==e)return e;var n=t(arguments);return n.push(a),r.apply(void 0,n)}var t=e("../internal/arrayCopy"),r=e("./assign"),a=e("../internal/assignDefaults");n.exports=l},{"../internal/arrayCopy":202,"../internal/assignDefaults":207,"./assign":273}],275:[function(e,n){n.exports=e("./assign")},{"./assign":273}],276:[function(e,n){function l(e,n){return e?r.call(e,n):!1}var t=Object.prototype,r=t.hasOwnProperty;n.exports=l},{}],277:[function(e,n){var l=e("../internal/isLength"),t=e("../lang/isNative"),r=e("../lang/isObject"),a=e("../internal/shimKeys"),o=t(o=Object.keys)&&o,u=o?function(e){if(e)var n=e.constructor,t=e.length;return"function"==typeof n&&n.prototype===e||"function"!=typeof e&&t&&l(t)?a(e):r(e)?o(e):[]}:a;n.exports=u},{"../internal/isLength":253,"../internal/shimKeys":257,"../lang/isNative":267,"../lang/isObject":269}],278:[function(e,n){function l(e){if(null==e)return[];u(e)||(e=Object(e));var n=e.length;n=n&&o(n)&&(r(e)||s.nonEnumArgs&&t(e))&&n||0;for(var l=e.constructor,i=-1,d="function"==typeof l&&l.prototype===e,p=Array(n),f=n>0;++i<n;)p[i]=i+"";for(var g in e)f&&a(g,n)||"constructor"==g&&(d||!c.call(e,g))||p.push(g);return p}var t=e("../lang/isArguments"),r=e("../lang/isArray"),a=e("../internal/isIndex"),o=e("../internal/isLength"),u=e("../lang/isObject"),s=e("../support"),i=Object.prototype,c=i.hasOwnProperty;n.exports=l},{"../internal/isIndex":251,"../internal/isLength":253,"../lang/isArguments":262,"../lang/isArray":263,"../lang/isObject":269,"../support":281}],279:[function(e,n){function l(e){return t(e,r(e))}var t=e("../internal/baseValues"),r=e("./keys");n.exports=l},{"../internal/baseValues":234,"./keys":277}],280:[function(e,n){function l(e){return e=t(e),e&&a.test(e)?e.replace(r,"\\$&"):e}var t=e("../internal/baseToString"),r=/[.*+?^${}()|[\]\/\\]/g,a=RegExp(r.source);n.exports=l},{"../internal/baseToString":232}],281:[function(e,n){(function(l){var t=e("./lang/isNative"),r=/\bthis\b/,a=Object.prototype,o=(o=l.window)&&o.document,u=a.propertyIsEnumerable,s={};!function(){s.funcDecomp=!t(l.WinRTError)&&r.test(function(){return this}),s.funcNames="string"==typeof Function.name;try{s.dom=11===o.createDocumentFragment().nodeType}catch(e){s.dom=!1}try{s.nonEnumArgs=!u.call(arguments,1)}catch(e){s.nonEnumArgs=!0}}(0,0),n.exports=s}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lang/isNative":267}],282:[function(e,n){function l(e){return function(){return e}}n.exports=l},{}],283:[function(e,n){function l(e){return e}n.exports=l},{}],284:[function(e,n,l){"use strict";function t(e,n,l){if(d)try{d.call(c,e,n,{value:l})}catch(t){e[n]=l}else e[n]=l}function r(e){return e&&(t(e,"call",e.call),t(e,"apply",e.apply)),e}function a(e){return p?p.call(c,e):(m.prototype=e||null,new m)}function o(){do var e=u(h.call(g.call(y(),36),2));while(f.call(x,e));return x[e]=e}function u(e){var n={};return n[e]=!0,Object.keys(n)[0]}function s(){return a(null)}function i(e){function n(n){function l(l,t){return l===u?t?a=null:a||(a=e(n)):void 0}var a;t(n,r,l)}function l(e){return f.call(e,r)||n(e),e[r](u)}var r=o(),u=a(null);return e=e||s,l.forget=function(e){f.call(e,r)&&e[r](u,!0)},l}var c=Object,d=Object.defineProperty,p=Object.create;r(d),r(p);var f=r(Object.prototype.hasOwnProperty),g=r(Number.prototype.toString),h=r(String.prototype.slice),m=function(){},y=Math.random,x=a(null);t(l,"makeUniqueKey",o);var b=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function(e){for(var n=b(e),l=0,t=0,r=n.length;r>l;++l)f.call(x,n[l])||(l>t&&(n[t]=n[l]),++t);return n.length=t,n},t(l,"makeAccessor",i)},{}],285:[function(e,n,l){function t(e){s.ok(this instanceof t),d.Identifier.assert(e),Object.defineProperties(this,{contextId:{value:e},listing:{value:[]},marked:{value:[!0]},finalLoc:{value:r()},tryEntries:{value:[]}}),Object.defineProperties(this,{leapManager:{value:new p.LeapManager(this)}})}function r(){return c.literal(-1)}function a(e){return d.BreakStatement.check(e)||d.ContinueStatement.check(e)||d.ReturnStatement.check(e)||d.ThrowStatement.check(e)}function o(e){return new Error("all declarations should have been transformed into assignments before the Exploder began its work: "+JSON.stringify(e))}function u(e){var n=e.type;return"normal"===n?!h.call(e,"target"):"break"===n||"continue"===n?!h.call(e,"value")&&d.Literal.check(e.target):"return"===n||"throw"===n?h.call(e,"value")&&!h.call(e,"target"):!1}var s=e("assert"),i=e("ast-types"),c=(i.builtInTypes.array,i.builders),d=i.namedTypes,p=e("./leap"),f=e("./meta"),g=e("./util"),h=Object.prototype.hasOwnProperty,m=t.prototype;l.Emitter=t,m.mark=function(e){d.Literal.assert(e);var n=this.listing.length;return-1===e.value?e.value=n:s.strictEqual(e.value,n),this.marked[n]=!0,e},m.emit=function(e){d.Expression.check(e)&&(e=c.expressionStatement(e)),d.Statement.assert(e),this.listing.push(e)},m.emitAssign=function(e,n){return this.emit(this.assign(e,n)),e},m.assign=function(e,n){return c.expressionStatement(c.assignmentExpression("=",e,n))},m.contextProperty=function(e,n){return c.memberExpression(this.contextId,n?c.literal(e):c.identifier(e),!!n)};var y={prev:!0,next:!0,sent:!0,rval:!0};m.isVolatileContextProperty=function(e){if(d.MemberExpression.check(e)){if(e.computed)return!0;if(d.Identifier.check(e.object)&&d.Identifier.check(e.property)&&e.object.name===this.contextId.name&&h.call(y,e.property.name))return!0}return!1},m.stop=function(e){e&&this.setReturnValue(e),this.jump(this.finalLoc)},m.setReturnValue=function(e){d.Expression.assert(e.value),this.emitAssign(this.contextProperty("rval"),this.explodeExpression(e))},m.clearPendingException=function(e,n){d.Literal.assert(e);var l=c.callExpression(this.contextProperty("catch",!0),[e]);n?this.emitAssign(n,l):this.emit(l)},m.jump=function(e){this.emitAssign(this.contextProperty("next"),e),this.emit(c.breakStatement())},m.jumpIf=function(e,n){d.Expression.assert(e),d.Literal.assert(n),this.emit(c.ifStatement(e,c.blockStatement([this.assign(this.contextProperty("next"),n),c.breakStatement()])))},m.jumpIfNot=function(e,n){d.Expression.assert(e),d.Literal.assert(n);var l;l=d.UnaryExpression.check(e)&&"!"===e.operator?e.argument:c.unaryExpression("!",e),this.emit(c.ifStatement(l,c.blockStatement([this.assign(this.contextProperty("next"),n),c.breakStatement()])))};var x=0;m.makeTempVar=function(){return this.contextProperty("t"+x++)},m.getContextFunction=function(e){var n=c.functionExpression(e||null,[this.contextId],c.blockStatement([this.getDispatchLoop()]),!1,!1);return n._aliasFunction=!0,n},m.getDispatchLoop=function(){var e,n=this,l=[],t=!1;return n.listing.forEach(function(r,o){n.marked.hasOwnProperty(o)&&(l.push(c.switchCase(c.literal(o),e=[])),t=!1),t||(e.push(r),a(r)&&(t=!0))}),this.finalLoc.value=this.listing.length,l.push(c.switchCase(this.finalLoc,[]),c.switchCase(c.literal("end"),[c.returnStatement(c.callExpression(this.contextProperty("stop"),[]))])),c.whileStatement(c.literal(1),c.switchStatement(c.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),l))},m.getTryLocsList=function(){if(0===this.tryEntries.length)return null;var e=0;return c.arrayExpression(this.tryEntries.map(function(n){var l=n.firstLoc.value;s.ok(l>=e,"try entries out of order"),e=l;var t=n.catchEntry,r=n.finallyEntry,a=[n.firstLoc,t?t.firstLoc:null];return r&&(a[2]=r.firstLoc,a[3]=r.afterLoc),c.arrayExpression(a)}))},m.explode=function(e,n){s.ok(e instanceof i.NodePath);var l=e.value,t=this;if(d.Node.assert(l),d.Statement.check(l))return t.explodeStatement(e);if(d.Expression.check(l))return t.explodeExpression(e,n);if(d.Declaration.check(l))throw o(l);switch(l.type){case"Program":return e.get("body").map(t.explodeStatement,t);case"VariableDeclarator":throw o(l);case"Property":case"SwitchCase":case"CatchClause":throw new Error(l.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(l.type))}},m.explodeStatement=function(e,n){s.ok(e instanceof i.NodePath);var l=e.value,t=this;if(d.Statement.assert(l),n?d.Identifier.assert(n):n=null,d.BlockStatement.check(l))return e.get("body").each(t.explodeStatement,t);if(!f.containsLeap(l))return void t.emit(l);switch(l.type){case"ExpressionStatement":t.explodeExpression(e.get("expression"),!0);break;case"LabeledStatement":var a=r();t.leapManager.withEntry(new p.LabeledEntry(a,l.label),function(){t.explodeStatement(e.get("body"),l.label)}),t.mark(a);break;case"WhileStatement":var o=r(),a=r();t.mark(o),t.jumpIfNot(t.explodeExpression(e.get("test")),a),t.leapManager.withEntry(new p.LoopEntry(a,o,n),function(){t.explodeStatement(e.get("body"))}),t.jump(o),t.mark(a);break;case"DoWhileStatement":var u=r(),h=r(),a=r();t.mark(u),t.leapManager.withEntry(new p.LoopEntry(a,h,n),function(){t.explode(e.get("body"))}),t.mark(h),t.jumpIf(t.explodeExpression(e.get("test")),u),t.mark(a);break;case"ForStatement":var m=r(),y=r(),a=r();l.init&&t.explode(e.get("init"),!0),t.mark(m),l.test&&t.jumpIfNot(t.explodeExpression(e.get("test")),a),t.leapManager.withEntry(new p.LoopEntry(a,y,n),function(){t.explodeStatement(e.get("body"))}),t.mark(y),l.update&&t.explode(e.get("update"),!0),t.jump(m),t.mark(a);break;case"ForInStatement":d.Identifier.assert(l.left);var m=r(),a=r(),x=t.makeTempVar();t.emitAssign(x,c.callExpression(g.runtimeProperty("keys"),[t.explodeExpression(e.get("right"))])),t.mark(m);var b=t.makeTempVar();t.jumpIf(c.memberExpression(c.assignmentExpression("=",b,c.callExpression(x,[])),c.identifier("done"),!1),a),t.emitAssign(l.left,c.memberExpression(b,c.identifier("value"),!1)),t.leapManager.withEntry(new p.LoopEntry(a,m,n),function(){t.explodeStatement(e.get("body"))}),t.jump(m),t.mark(a);break;case"BreakStatement":t.emitAbruptCompletion({type:"break",target:t.leapManager.getBreakLoc(l.label)});break;case"ContinueStatement":t.emitAbruptCompletion({type:"continue",target:t.leapManager.getContinueLoc(l.label)});break;case"SwitchStatement":for(var _=t.emitAssign(t.makeTempVar(),t.explodeExpression(e.get("discriminant"))),a=r(),v=r(),I=v,E=[],k=l.cases||[],w=k.length-1;w>=0;--w){var R=k[w];d.SwitchCase.assert(R),R.test?I=c.conditionalExpression(c.binaryExpression("===",_,R.test),E[w]=r(),I):E[w]=v}t.jump(t.explodeExpression(new i.NodePath(I,e,"discriminant"))),t.leapManager.withEntry(new p.SwitchEntry(a),function(){e.get("cases").each(function(e){var n=(e.value,e.name);t.mark(E[n]),e.get("consequent").each(t.explodeStatement,t)})}),t.mark(a),-1===v.value&&(t.mark(v),s.strictEqual(a.value,v.value));break;case"IfStatement":var S=l.alternate&&r(),a=r();t.jumpIfNot(t.explodeExpression(e.get("test")),S||a),t.explodeStatement(e.get("consequent")),S&&(t.jump(a),t.mark(S),t.explodeStatement(e.get("alternate"))),t.mark(a);break;case"ReturnStatement":t.emitAbruptCompletion({type:"return",value:t.explodeExpression(e.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var a=r(),C=l.handler;!C&&l.handlers&&(C=l.handlers[0]||null);var A=C&&r(),j=A&&new p.CatchEntry(A,C.param),T=l.finalizer&&r(),L=T&&new p.FinallyEntry(T,a),P=new p.TryEntry(t.getUnmarkedCurrentLoc(),j,L);t.tryEntries.push(P),t.updateContextPrevLoc(P.firstLoc),t.leapManager.withEntry(P,function(){if(t.explodeStatement(e.get("block")),A){t.jump(T?T:a),t.updateContextPrevLoc(t.mark(A));var n=e.get("handler","body"),l=t.makeTempVar();t.clearPendingException(P.firstLoc,l);var r=n.scope,o=C.param.name;d.CatchClause.assert(r.node),s.strictEqual(r.lookup(o),r),i.visit(n,{visitIdentifier:function(e){return g.isReference(e,o)&&e.scope.lookup(o)===r?l:void this.traverse(e)},visitFunction:function(e){return e.scope.declares(o)?!1:void this.traverse(e)}}),t.leapManager.withEntry(j,function(){t.explodeStatement(n)})}T&&(t.updateContextPrevLoc(t.mark(T)),t.leapManager.withEntry(L,function(){t.explodeStatement(e.get("finalizer"))}),t.emit(c.returnStatement(c.callExpression(t.contextProperty("finish"),[L.firstLoc]))))}),t.mark(a);break;case"ThrowStatement":t.emit(c.throwStatement(t.explodeExpression(e.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(l.type))}},m.emitAbruptCompletion=function(e){u(e)||s.ok(!1,"invalid completion record: "+JSON.stringify(e)),s.notStrictEqual(e.type,"normal","normal completions are not abrupt");var n=[c.literal(e.type)];"break"===e.type||"continue"===e.type?(d.Literal.assert(e.target),n[1]=e.target):("return"===e.type||"throw"===e.type)&&e.value&&(d.Expression.assert(e.value),n[1]=e.value),this.emit(c.returnStatement(c.callExpression(this.contextProperty("abrupt"),n)))},m.getUnmarkedCurrentLoc=function(){return c.literal(this.listing.length)},m.updateContextPrevLoc=function(e){e?(d.Literal.assert(e),-1===e.value?e.value=this.listing.length:s.strictEqual(e.value,this.listing.length)):e=this.getUnmarkedCurrentLoc(),this.emitAssign(this.contextProperty("prev"),e)},m.explodeExpression=function(e,n){function l(e){return d.Expression.assert(e),n?void u.emit(e):e}function t(e,n,l){s.ok(n instanceof i.NodePath),s.ok(!l||!e,"Ignoring the result of a child expression but forcing it to be assigned to a temporary variable?");var t=u.explodeExpression(n,l);return l||(e||p&&(u.isVolatileContextProperty(t)||f.hasSideEffects(t)))&&(t=u.emitAssign(e||u.makeTempVar(),t)),t}s.ok(e instanceof i.NodePath);var a=e.value;if(!a)return a;d.Expression.assert(a);var o,u=this;if(!f.containsLeap(a))return l(a);var p=f.containsLeap.onlyChildren(a);switch(a.type){case"MemberExpression":return l(c.memberExpression(u.explodeExpression(e.get("object")),a.computed?t(null,e.get("property")):a.property,a.computed));case"CallExpression":var g=e.get("callee"),h=u.explodeExpression(g);return!d.MemberExpression.check(g.node)&&d.MemberExpression.check(h)&&(h=c.sequenceExpression([c.literal(0),h])),l(c.callExpression(h,e.get("arguments").map(function(e){return t(null,e)})));case"NewExpression":return l(c.newExpression(t(null,e.get("callee")),e.get("arguments").map(function(e){return t(null,e)})));case"ObjectExpression":return l(c.objectExpression(e.get("properties").map(function(e){return c.property(e.value.kind,e.value.key,t(null,e.get("value")))})));case"ArrayExpression":return l(c.arrayExpression(e.get("elements").map(function(e){return t(null,e)})));case"SequenceExpression":var m=a.expressions.length-1;return e.get("expressions").each(function(e){e.name===m?o=u.explodeExpression(e,n):u.explodeExpression(e,!0)}),o;case"LogicalExpression":var y=r();n||(o=u.makeTempVar());var x=t(o,e.get("left"));return"&&"===a.operator?u.jumpIfNot(x,y):(s.strictEqual(a.operator,"||"),u.jumpIf(x,y)),t(o,e.get("right"),n),u.mark(y),o;case"ConditionalExpression":var b=r(),y=r(),_=u.explodeExpression(e.get("test"));return u.jumpIfNot(_,b),n||(o=u.makeTempVar()),t(o,e.get("consequent"),n),u.jump(y),u.mark(b),t(o,e.get("alternate"),n),u.mark(y),o;case"UnaryExpression":return l(c.unaryExpression(a.operator,u.explodeExpression(e.get("argument")),!!a.prefix));case"BinaryExpression":return l(c.binaryExpression(a.operator,t(null,e.get("left")),t(null,e.get("right"))));case"AssignmentExpression":return l(c.assignmentExpression(a.operator,u.explodeExpression(e.get("left")),u.explodeExpression(e.get("right"))));case"UpdateExpression":return l(c.updateExpression(a.operator,u.explodeExpression(e.get("argument")),a.prefix));case"YieldExpression":var y=r(),v=a.argument&&u.explodeExpression(e.get("argument"));if(v&&a.delegate){var o=u.makeTempVar();return u.emit(c.returnStatement(c.callExpression(u.contextProperty("delegateYield"),[v,c.literal(o.property.name),y]))),u.mark(y),o}return u.emitAssign(u.contextProperty("next"),y),u.emit(c.returnStatement(v||null)),u.mark(y),u.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(a.type))}}},{"./leap":287,"./meta":288,"./util":289,assert:136,"ast-types":134}],286:[function(e,n,l){var t=e("assert"),r=e("ast-types"),a=r.namedTypes,o=r.builders,u=Object.prototype.hasOwnProperty;l.hoist=function(e){function n(e,n){a.VariableDeclaration.assert(e);var t=[];return e.declarations.forEach(function(e){l[e.id.name]=e.id,e.init?t.push(o.assignmentExpression("=",e.id,e.init)):n&&t.push(e.id)}),0===t.length?null:1===t.length?t[0]:o.sequenceExpression(t)}t.ok(e instanceof r.NodePath),a.Function.assert(e.value);
var l={};r.visit(e.get("body"),{visitVariableDeclaration:function(e){var l=n(e.value,!1);return null!==l?o.expressionStatement(l):(e.replace(),!1)},visitForStatement:function(e){var l=e.value.init;a.VariableDeclaration.check(l)&&e.get("init").replace(n(l,!1)),this.traverse(e)},visitForInStatement:function(e){var l=e.value.left;a.VariableDeclaration.check(l)&&e.get("left").replace(n(l,!0)),this.traverse(e)},visitFunctionDeclaration:function(e){var n=e.value;l[n.id.name]=n.id;var t=(e.parent.node,o.expressionStatement(o.assignmentExpression("=",n.id,o.functionExpression(n.id,n.params,n.body,n.generator,n.expression))));return a.BlockStatement.check(e.parent.node)?(e.parent.get("body").unshift(t),e.replace()):e.replace(t),!1},visitFunctionExpression:function(){return!1}});var s={};e.get("params").each(function(e){var n=e.value;a.Identifier.check(n)&&(s[n.name]=n)});var i=[];return Object.keys(l).forEach(function(e){u.call(s,e)||i.push(o.variableDeclarator(l[e],null))}),0===i.length?null:o.variableDeclaration("var",i)}},{assert:136,"ast-types":134}],287:[function(e,n,l){function t(){p.ok(this instanceof t)}function r(e){t.call(this),g.Literal.assert(e),this.returnLoc=e}function a(e,n,l){t.call(this),g.Literal.assert(e),g.Literal.assert(n),l?g.Identifier.assert(l):l=null,this.breakLoc=e,this.continueLoc=n,this.label=l}function o(e){t.call(this),g.Literal.assert(e),this.breakLoc=e}function u(e,n,l){t.call(this),g.Literal.assert(e),n?p.ok(n instanceof s):n=null,l?p.ok(l instanceof i):l=null,p.ok(n||l),this.firstLoc=e,this.catchEntry=n,this.finallyEntry=l}function s(e,n){t.call(this),g.Literal.assert(e),g.Identifier.assert(n),this.firstLoc=e,this.paramId=n}function i(e,n){t.call(this),g.Literal.assert(e),g.Literal.assert(n),this.firstLoc=e,this.afterLoc=n}function c(e,n){t.call(this),g.Literal.assert(e),g.Identifier.assert(n),this.breakLoc=e,this.label=n}function d(n){p.ok(this instanceof d);var l=e("./emit").Emitter;p.ok(n instanceof l),this.emitter=n,this.entryStack=[new r(n.finalLoc)]}{var p=e("assert"),f=e("ast-types"),g=f.namedTypes,h=(f.builders,e("util").inherits);Object.prototype.hasOwnProperty}h(r,t),l.FunctionEntry=r,h(a,t),l.LoopEntry=a,h(o,t),l.SwitchEntry=o,h(u,t),l.TryEntry=u,h(s,t),l.CatchEntry=s,h(i,t),l.FinallyEntry=i,h(c,t),l.LabeledEntry=c;var m=d.prototype;l.LeapManager=d,m.withEntry=function(e,n){p.ok(e instanceof t),this.entryStack.push(e);try{n.call(this.emitter)}finally{var l=this.entryStack.pop();p.strictEqual(l,e)}},m._findLeapLocation=function(e,n){for(var l=this.entryStack.length-1;l>=0;--l){var t=this.entryStack[l],r=t[e];if(r)if(n){if(t.label&&t.label.name===n.name)return r}else if(!(t instanceof c))return r}return null},m.getBreakLoc=function(e){return this._findLeapLocation("breakLoc",e)},m.getContinueLoc=function(e){return this._findLeapLocation("continueLoc",e)}},{"./emit":285,assert:136,"ast-types":134,util:161}],288:[function(e,n,l){function t(e,n){function l(e){function n(e){return l||(u.check(e)?e.some(n):s.Node.check(e)&&(r.strictEqual(l,!1),l=t(e))),l}s.Node.assert(e);var l=!1;return o.eachField(e,function(e,l){n(l)}),l}function t(t){s.Node.assert(t);var r=a(t);return i.call(r,e)?r[e]:r[e]=i.call(c,t.type)?!1:i.call(n,t.type)?!0:l(t)}return t.onlyChildren=l,t}var r=e("assert"),a=e("private").makeAccessor(),o=e("ast-types"),u=o.builtInTypes.array,s=o.namedTypes,i=Object.prototype.hasOwnProperty,c={FunctionExpression:!0},d={CallExpression:!0,ForInStatement:!0,UnaryExpression:!0,BinaryExpression:!0,AssignmentExpression:!0,UpdateExpression:!0,NewExpression:!0},p={YieldExpression:!0,BreakStatement:!0,ContinueStatement:!0,ReturnStatement:!0,ThrowStatement:!0};for(var f in p)i.call(p,f)&&(d[f]=p[f]);l.hasSideEffects=t("hasSideEffects",d),l.containsLeap=t("containsLeap",p)},{assert:136,"ast-types":134,"private":284}],289:[function(e,n,l){var t=(e("assert"),e("ast-types")),r=t.namedTypes,a=t.builders,o=Object.prototype.hasOwnProperty;l.defaults=function(e){for(var n,l=arguments.length,t=1;l>t;++t)if(n=arguments[t])for(var r in n)o.call(n,r)&&!o.call(e,r)&&(e[r]=n[r]);return e},l.runtimeProperty=function(e){return a.memberExpression(a.identifier("regeneratorRuntime"),a.identifier(e),!1)},l.isReference=function(e,n){var l=e.value;if(!r.Identifier.check(l))return!1;if(n&&l.name!==n)return!1;var t=e.parent.value;switch(t.type){case"VariableDeclarator":return"init"===e.name;case"MemberExpression":return"object"===e.name||t.computed&&"property"===e.name;case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":return"id"===e.name?!1:t.params===e.parentPath&&t.params[e.name]===l?!1:!0;case"ClassDeclaration":case"ClassExpression":return"id"!==e.name;case"CatchClause":return"param"!==e.name;case"Property":case"MethodDefinition":return"key"!==e.name;case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return!1;default:return!0}}},{assert:136,"ast-types":134}],290:[function(e,n,l){var t=(e("assert"),e("fs"),e("ast-types")),r=t.namedTypes,a=t.builders,o=(t.builtInTypes.array,t.builtInTypes.object,t.NodePath),u=e("./hoist").hoist,s=e("./emit").Emitter,i=e("./util").runtimeProperty;l.transform=function(e,n){n=n||{};var l=e instanceof o?e:new o(e);return c.visit(l,n),e=l.value,n.madeChanges=c.wasChangeReported(),e};var c=t.PathVisitor.fromMethodsObject({reset:function(e,n){this.options=n},visitFunction:function(e){this.traverse(e);var n=e.value,l=n.async&&!this.options.disableAsync;if(n.generator||l){this.reportChanged(),n.generator=!1,n.expression&&(n.expression=!1,n.body=a.blockStatement([a.returnStatement(n.body)])),l&&d.visit(e.get("body"));var t=n.id||(n.id=e.scope.parent.declareTemporary("callee$")),o=[],c=e.value.body;c.body=c.body.filter(function(e){return e&&null!=e._blockHoist?(o.push(e),!1):!0});var p=a.identifier(n.id.name+"$"),f=e.scope.declareTemporary("context$"),g=u(e),h=new s(f);h.explode(e.get("body")),g&&g.declarations.length>0&&o.push(g);var m=[h.getContextFunction(p),l?a.literal(null):t,a.thisExpression()],y=h.getTryLocsList();y&&m.push(y);var x=a.callExpression(i(l?"async":"wrap"),m);if(o.push(a.returnStatement(x)),n.body=a.blockStatement(o),n.body._declarations=c._declarations,l)return void(n.async=!1);if(!r.FunctionDeclaration.check(n))return r.FunctionExpression.assert(n),a.callExpression(i("mark"),[n]);for(var b=e.parent;b&&!r.BlockStatement.check(b.value)&&!r.Program.check(b.value);)b=b.parent;if(b){e.replace(),n.type="FunctionExpression";var _=a.variableDeclaration("var",[a.variableDeclarator(n.id,a.callExpression(i("mark"),[n]))]);n.comments&&(_.leadingComments=n.leadingComments,_.trailingComments=n.trailingComments,n.leadingComments=null,n.trailingComments=null),_._blockHoist=3;{var v=b.get("body");v.value.length}v.push(_)}}}}),d=t.PathVisitor.fromMethodsObject({visitFunction:function(){return!1},visitAwaitExpression:function(e){var n=e.value.argument;return e.value.all&&(n=a.callExpression(a.memberExpression(a.identifier("Promise"),a.identifier("all"),!1),[n])),a.yieldExpression(n,!1)}})},{"./emit":285,"./hoist":286,"./util":289,assert:136,"ast-types":134,fs:135}],291:[function(e,n){(function(l){function t(e,n){function l(e){r.push(e)}function t(){this.queue(compile(r.join(""),n).code),this.queue(null)}var r=[];return o(l,t)}function r(){e("./runtime")}{var a=(e("assert"),e("path")),o=(e("fs"),e("through")),u=e("./lib/visit").transform;e("./lib/util"),e("ast-types")}n.exports=t,t.runtime=r,r.path=a.join(l,"runtime.js"),t.transform=u}).call(this,"/node_modules/regenerator-babel")},{"./lib/util":289,"./lib/visit":290,"./runtime":293,assert:136,"ast-types":134,fs:135,path:144,through:292}],292:[function(e,n,l){(function(t){function r(e,n,l){function r(){for(;i.length&&!d.paused;){var e=i.shift();if(null===e)return d.emit("end");d.emit("data",e)}}function o(){d.writable=!1,n.call(d),!d.readable&&d.autoDestroy&&d.destroy()}e=e||function(e){this.queue(e)},n=n||function(){this.queue(null)};var u=!1,s=!1,i=[],c=!1,d=new a;return d.readable=d.writable=!0,d.paused=!1,d.autoDestroy=!(l&&l.autoDestroy===!1),d.write=function(n){return e.call(this,n),!d.paused},d.queue=d.push=function(e){return c?d:(null==e&&(c=!0),i.push(e),r(),d)},d.on("end",function(){d.readable=!1,!d.writable&&d.autoDestroy&&t.nextTick(function(){d.destroy()})}),d.end=function(e){return u?void 0:(u=!0,arguments.length&&d.write(e),o(),d)},d.destroy=function(){return s?void 0:(s=!0,u=!0,i.length=0,d.writable=d.readable=!1,d.emit("close"),d)},d.pause=function(){return d.paused?void 0:(d.paused=!0,d)},d.resume=function(){return d.paused&&(d.paused=!1,d.emit("resume")),r(),d.paused||d.emit("drain"),d},d}var a=e("stream");l=n.exports=r,r.through=r}).call(this,e("_process"))},{_process:145,stream:157}],293:[function(e,n){(function(e){!function(e){"use strict";function l(e,n,l,t){return new o(e,n,l||null,t||[])}function t(e,n,l){try{return{type:"normal",arg:e.call(n,l)}}catch(t){return{type:"throw",arg:t}}}function r(){}function a(){}function o(e,n,l,r){function a(n,r){if(s===b)throw new Error("Generator is already running");if(s===_)return d();for(;;){var a=u.delegate;if(a){var o=t(a.iterator[n],a.iterator,r);if("throw"===o.type){u.delegate=null,n="throw",r=o.arg;continue}n="next",r=p;var i=o.arg;if(!i.done)return s=x,i;u[a.resultName]=i.value,u.next=a.nextLoc,u.delegate=null}if("next"===n){if(s===y&&"undefined"!=typeof r)throw new TypeError("attempt to send "+JSON.stringify(r)+" to newborn generator");s===x?u.sent=r:delete u.sent}else if("throw"===n){if(s===y)throw s=_,r;u.dispatchException(r)&&(n="next",r=p)}else"return"===n&&u.abrupt("return",r);s=b;var o=t(e,l,u);if("normal"===o.type){s=u.done?_:x;var i={value:o.arg,done:u.done};if(o.arg!==v)return i;u.delegate&&"next"===n&&(r=p)}else"throw"===o.type&&(s=_,"next"===n?u.dispatchException(o.arg):r=o.arg)}}var o=n?Object.create(n.prototype):this,u=new i(r),s=y;return o.next=a.bind(o,"next"),o["throw"]=a.bind(o,"throw"),o["return"]=a.bind(o,"return"),o}function u(e){var n={tryLoc:e[0]};1 in e&&(n.catchLoc=e[1]),2 in e&&(n.finallyLoc=e[2],n.afterLoc=e[3]),this.tryEntries.push(n)}function s(e){var n=e.completion||{};n.type="normal",delete n.arg,e.completion=n}function i(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(u,this),this.reset()}function c(e){if(e){var n=e[g];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var l=-1,t=function r(){for(;++l<e.length;)if(f.call(e,l))return r.value=e[l],r.done=!1,r;return r.value=p,r.done=!0,r};return t.next=t}}return{next:d}}function d(){return{value:p,done:!0}}var p,f=Object.prototype.hasOwnProperty,g="function"==typeof Symbol&&Symbol.iterator||"@@iterator",h="object"==typeof n,m=e.regeneratorRuntime;if(m)return void(h&&(n.exports=m));m=e.regeneratorRuntime=h?n.exports:{},m.wrap=l;var y="suspendedStart",x="suspendedYield",b="executing",_="completed",v={},I=a.prototype=o.prototype;r.prototype=I.constructor=a,a.constructor=r,r.displayName="GeneratorFunction",m.isGeneratorFunction=function(e){var n="function"==typeof e&&e.constructor;return n?n===r||"GeneratorFunction"===(n.displayName||n.name):!1},m.mark=function(e){return e.__proto__=a,e.prototype=Object.create(I),e},m.async=function(e,n,r,a){return new Promise(function(o,u){function s(e){var n=t(this,null,e);if("throw"===n.type)return void u(n.arg);var l=n.arg;l.done?o(l.value):Promise.resolve(l.value).then(c,d)}var i=l(e,n,r,a),c=s.bind(i.next),d=s.bind(i["throw"]);c()})},I[g]=function(){return this},I.toString=function(){return"[object Generator]"},m.keys=function(e){var n=[];for(var l in e)n.push(l);return n.reverse(),function t(){for(;n.length;){var l=n.pop();if(l in e)return t.value=l,t.done=!1,t}return t.done=!0,t}},m.values=c,i.prototype={constructor:i,reset:function(){this.prev=0,this.next=0,this.sent=p,this.done=!1,this.delegate=null,this.tryEntries.forEach(s);for(var e,n=0;f.call(this,e="t"+n)||20>n;++n)this[e]=null},stop:function(){this.done=!0;var e=this.tryEntries[0],n=e.completion;if("throw"===n.type)throw n.arg;return this.rval},dispatchException:function(e){function n(n,t){return a.type="throw",a.arg=e,l.next=n,!!t}if(this.done)throw e;for(var l=this,t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t],a=r.completion;if("root"===r.tryLoc)return n("end");if(r.tryLoc<=this.prev){var o=f.call(r,"catchLoc"),u=f.call(r,"finallyLoc");if(o&&u){if(this.prev<r.catchLoc)return n(r.catchLoc,!0);if(this.prev<r.finallyLoc)return n(r.finallyLoc)}else if(o){if(this.prev<r.catchLoc)return n(r.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<r.finallyLoc)return n(r.finallyLoc)}}}},_findFinallyEntry:function(e){for(var n=this.tryEntries.length-1;n>=0;--n){var l=this.tryEntries[n];if(l.tryLoc<=this.prev&&f.call(l,"finallyLoc")&&(l.finallyLoc===e||this.prev<l.finallyLoc))return l}},abrupt:function(e,n){var l=this._findFinallyEntry(),t=l?l.completion:{};return t.type=e,t.arg=n,l?this.next=l.finallyLoc:this.complete(t),v},complete:function(e,n){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=e.arg,this.next="end"):"normal"===e.type&&n&&(this.next=n),v},finish:function(e){var n=this._findFinallyEntry(e);return this.complete(n.completion,n.afterLoc)},"catch":function(e){for(var n=this.tryEntries.length-1;n>=0;--n){var l=this.tryEntries[n];if(l.tryLoc===e){var t=l.completion;if("throw"===t.type){var r=t.arg;s(l)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,l){return this.delegate={iterator:c(e),resultName:n,nextLoc:l},v}}}("object"==typeof e?e:"object"==typeof window?window:this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],294:[function(e,n,l){var t=e("regenerate");l.REGULAR={d:t().addRange(48,57),D:t().addRange(0,47).addRange(58,65535),s:t(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:t().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:t(95).addRange(48,57).addRange(65,90).addRange(97,122),W:t(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)},l.UNICODE={d:t().addRange(48,57),D:t().addRange(0,47).addRange(58,1114111),s:t(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:t().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:t(95).addRange(48,57).addRange(65,90).addRange(97,122),W:t(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)},l.UNICODE_IGNORE_CASE={d:t().addRange(48,57),D:t().addRange(0,47).addRange(58,1114111),s:t(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:t().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:t(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:t(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:296}],295:[function(e,n){n.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}},{}],296:[function(n,l,t){(function(n){!function(r){var a="object"==typeof t&&t,o="object"==typeof l&&l&&l.exports==a&&l,u="object"==typeof n&&n;(u.global===u||u.window===u)&&(r=u);var s={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."},i=55296,c=56319,d=56320,p=57343,f=/\\x00([^0123456789]|$)/g,g={},h=g.hasOwnProperty,m=function(e,n){var l;for(l in n)h.call(n,l)&&(e[l]=n[l]);return e},y=function(e,n){for(var l=-1,t=e.length;++l<t;)n(e[l],l)},x=g.toString,b=function(e){return"[object Array]"==x.call(e)},_=function(e){return"number"==typeof e||"[object Number]"==x.call(e)},v="0000",I=function(e,n){var l=String(e);return l.length<n?(v+l).slice(-n):l},E=function(e){return Number(e).toString(16).toUpperCase()},k=[].slice,w=function(e){for(var n,l=-1,t=e.length,r=t-1,a=[],o=!0,u=0;++l<t;)if(n=e[l],o)a.push(n),u=n,o=!1;else if(n==u+1){if(l!=r){u=n;continue}o=!0,a.push(n+1)}else a.push(u+1,n),u=n;return o||a.push(n+1),a},R=function(e,n){for(var l,t,r=0,a=e.length;a>r;){if(l=e[r],t=e[r+1],n>=l&&t>n)return n==l?t==l+1?(e.splice(r,2),e):(e[r]=n+1,e):n==t-1?(e[r+1]=n,e):(e.splice(r,2,l,n,n+1,t),e);r+=2}return e},S=function(e,n,l){if(n>l)throw Error(s.rangeOrder);for(var t,r,a=0;a<e.length;){if(t=e[a],r=e[a+1]-1,t>l)return e;if(t>=n&&l>=r)e.splice(a,2);else{if(n>=t&&r>l)return n==t?(e[a]=l+1,e[a+1]=r+1,e):(e.splice(a,2,t,n,l+1,r+1),e);if(n>=t&&r>=n)e[a+1]=n;else if(l>=t&&r>=l)return e[a]=l+1,e;a+=2}}return e},C=function(e,n){var l,t,r=0,a=null,o=e.length;if(0>n||n>1114111)throw RangeError(s.codePointRange);for(;o>r;){if(l=e[r],t=e[r+1],n>=l&&t>n)return e;if(n==l-1)return e[r]=n,e;if(l>n)return e.splice(null!=a?a+2:0,0,n,n+1),e;if(n==t)return n+1==e[r+2]?(e.splice(r,4,l,e[r+3]),e):(e[r+1]=n+1,e);a=r,r+=2}return e.push(n,n+1),e},A=function(e,n){for(var l,t,r=0,a=e.slice(),o=n.length;o>r;)l=n[r],t=n[r+1]-1,a=l==t?C(a,l):T(a,l,t),r+=2;return a},j=function(e,n){for(var l,t,r=0,a=e.slice(),o=n.length;o>r;)l=n[r],t=n[r+1]-1,a=l==t?R(a,l):S(a,l,t),r+=2;return a},T=function(e,n,l){if(n>l)throw Error(s.rangeOrder);if(0>n||n>1114111||0>l||l>1114111)throw RangeError(s.codePointRange);for(var t,r,a=0,o=!1,u=e.length;u>a;){if(t=e[a],r=e[a+1],o){if(t==l+1)return e.splice(a-1,2),e;if(t>l)return e;t>=n&&l>=t&&(r>n&&l>=r-1?(e.splice(a,2),a-=2):(e.splice(a-1,2),a-=2))}else{if(t==l+1)return e[a]=n,e;if(t>l)return e.splice(a,0,n,l+1),e;if(n>=t&&r>n&&r>=l+1)return e;n>=t&&r>n||r==n?(e[a+1]=l+1,o=!0):t>=n&&l+1>=r&&(e[a]=n,e[a+1]=l+1,o=!0)}a+=2}return o||e.push(n,l+1),e},L=function(e,n){var l=0,t=e.length,r=e[l],a=e[t-1];if(t>=2&&(r>n||n>a))return!1;for(;t>l;){if(r=e[l],a=e[l+1],n>=r&&a>n)return!0;l+=2}return!1},P=function(e,n){for(var l,t=0,r=n.length,a=[];r>t;)l=n[t],L(e,l)&&a.push(l),++t;return w(a)},O=function(e){return!e.length},M=function(e){return 2==e.length&&e[0]+1==e[1]},D=function(e){for(var n,l,t=0,r=[],a=e.length;a>t;){for(n=e[t],l=e[t+1];l>n;)r.push(n),++n;t+=2}return r},N=Math.floor,B=function(e){return parseInt(N((e-65536)/1024)+i,10)},F=function(e){return parseInt((e-65536)%1024+d,10)},V=String.fromCharCode,U=function(e){var n;return n=9==e?"\\t":10==e?"\\n":12==e?"\\f":13==e?"\\r":92==e?"\\\\":36==e||e>=40&&43>=e||45==e||46==e||63==e||e>=91&&94>=e||e>=123&&125>=e?"\\"+V(e):e>=32&&126>=e?V(e):255>=e?"\\x"+I(E(e),2):"\\u"+I(E(e),4)},q=function(e){var n,l=e.length,t=e.charCodeAt(0);return t>=i&&c>=t&&l>1?(n=e.charCodeAt(1),1024*(t-i)+n-d+65536):t},G=function(e){var n,l,t="",r=0,a=e.length;if(M(e))return U(e[0]);for(;a>r;)n=e[r],l=e[r+1]-1,t+=n==l?U(n):n+1==l?U(n)+U(l):U(n)+"-"+U(l),r+=2;return"["+t+"]"},H=function(e){for(var n,l,t=[],r=[],a=[],o=[],u=0,s=e.length;s>u;)n=e[u],l=e[u+1]-1,i>n?(i>l&&a.push(n,l+1),l>=i&&c>=l&&(a.push(n,i),t.push(i,l+1)),l>=d&&p>=l&&(a.push(n,i),t.push(i,c+1),r.push(d,l+1)),l>p&&(a.push(n,i),t.push(i,c+1),r.push(d,p+1),65535>=l?a.push(p+1,l+1):(a.push(p+1,65536),o.push(65536,l+1)))):n>=i&&c>=n?(l>=i&&c>=l&&t.push(n,l+1),l>=d&&p>=l&&(t.push(n,c+1),r.push(d,l+1)),l>p&&(t.push(n,c+1),r.push(d,p+1),65535>=l?a.push(p+1,l+1):(a.push(p+1,65536),o.push(65536,l+1)))):n>=d&&p>=n?(l>=d&&p>=l&&r.push(n,l+1),l>p&&(r.push(n,p+1),65535>=l?a.push(p+1,l+1):(a.push(p+1,65536),o.push(65536,l+1)))):n>p&&65535>=n?65535>=l?a.push(n,l+1):(a.push(n,65536),o.push(65536,l+1)):o.push(n,l+1),u+=2;return{loneHighSurrogates:t,loneLowSurrogates:r,bmp:a,astral:o}},X=function(e){for(var n,l,t,r,a,o,u=[],s=[],i=!1,c=-1,d=e.length;++c<d;)if(n=e[c],l=e[c+1]){for(t=n[0],r=n[1],a=l[0],o=l[1],s=r;a&&t[0]==a[0]&&t[1]==a[1];)s=M(o)?C(s,o[0]):T(s,o[0],o[1]-1),++c,n=e[c],t=n[0],r=n[1],l=e[c+1],a=l&&l[0],o=l&&l[1],i=!0;u.push([t,i?s:r]),i=!1}else u.push(n);return W(u)},W=function(e){if(1==e.length)return e;for(var n=-1,l=-1;++n<e.length;){var t=e[n],r=t[1],a=r[0],o=r[1];for(l=n;++l<e.length;){var u=e[l],s=u[1],i=s[0],c=s[1];a==i&&o==c&&(t[0]=M(u[0])?C(t[0],u[0][0]):T(t[0],u[0][0],u[0][1]-1),e.splice(l,1),--l)}}return e},J=function(e){if(!e.length)return[];for(var n,l,t,r,a,o,u=0,s=0,i=0,c=[],f=e.length;f>u;){n=e[u],l=e[u+1]-1,t=B(n),r=F(n),a=B(l),o=F(l);var g=r==d,h=o==p,m=!1;t==a||g&&h?(c.push([[t,a+1],[r,o+1]]),m=!0):c.push([[t,t+1],[r,p+1]]),!m&&a>t+1&&(h?(c.push([[t+1,a+1],[d,o+1]]),m=!0):c.push([[t+1,a],[d,p+1]])),m||c.push([[a,a+1],[d,o+1]]),s=t,i=a,u+=2}return X(c)},Y=function(e){var n=[];return y(e,function(e){var l=e[0],t=e[1];n.push(G(l)+G(t))}),n.join("|")},z=function(e,n){var l=[],t=H(e),r=t.loneHighSurrogates,a=t.loneLowSurrogates,o=t.bmp,u=t.astral,s=(!O(t.astral),!O(r)),i=!O(a),c=J(u);return n&&(o=A(o,r),s=!1,o=A(o,a),i=!1),O(o)||l.push(G(o)),c.length&&l.push(Y(c)),s&&l.push(G(r)+"(?![\\uDC00-\\uDFFF])"),i&&l.push("(?:[^\\uD800-\\uDBFF]|^)"+G(a)),l.join("|")},K=function(e){return arguments.length>1&&(e=k.call(arguments)),this instanceof K?(this.data=[],e?this.add(e):this):(new K).add(e)};K.version="1.2.0";var $=K.prototype;m($,{add:function(e){var n=this;return null==e?n:e instanceof K?(n.data=A(n.data,e.data),n):(arguments.length>1&&(e=k.call(arguments)),b(e)?(y(e,function(e){n.add(e)}),n):(n.data=C(n.data,_(e)?e:q(e)),n))},remove:function(e){var n=this;return null==e?n:e instanceof K?(n.data=j(n.data,e.data),n):(arguments.length>1&&(e=k.call(arguments)),b(e)?(y(e,function(e){n.remove(e)}),n):(n.data=R(n.data,_(e)?e:q(e)),n))},addRange:function(e,n){var l=this;return l.data=T(l.data,_(e)?e:q(e),_(n)?n:q(n)),l},removeRange:function(e,n){var l=this,t=_(e)?e:q(e),r=_(n)?n:q(n);return l.data=S(l.data,t,r),l},intersection:function(e){var n=this,l=e instanceof K?D(e.data):e;return n.data=P(n.data,l),n},contains:function(e){return L(this.data,_(e)?e:q(e))},clone:function(){var e=new K;return e.data=this.data.slice(0),e},toString:function(e){var n=z(this.data,e?e.bmpOnly:!1);return n.replace(f,"\\0$1")},toRegExp:function(e){return RegExp(this.toString(),e||"")},valueOf:function(){return D(this.data)}}),$.toArray=$.valueOf,"function"==typeof e&&"object"==typeof e.amd&&e.amd?e(function(){return K}):a&&!a.nodeType?o?o.exports=K:a.regenerate=K:r.regenerate=K}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],297:[function(n,l,t){(function(n){(function(){"use strict";function r(){var e,n,l=16384,t=[],r=-1,a=arguments.length;if(!a)return"";for(var o="";++r<a;){var u=Number(arguments[r]);if(!isFinite(u)||0>u||u>1114111||S(u)!=u)throw RangeError("Invalid code point: "+u);65535>=u?t.push(u):(u-=65536,e=(u>>10)+55296,n=u%1024+56320,t.push(e,n)),(r+1==a||t.length>l)&&(o+=R.apply(null,t),t.length=0)}return o}function a(e,n){if(-1==n.indexOf("|")){if(e==n)return;throw Error("Invalid node type: "+e)}if(n=a.hasOwnProperty(n)?a[n]:a[n]=RegExp("^(?:"+n+")$"),!n.test(e))throw Error("Invalid node type: "+e)}function o(e){var n=e.type;if(o.hasOwnProperty(n)&&"function"==typeof o[n])return o[n](e);throw Error("Invalid node type: "+n)}function u(e){a(e.type,"alternative");var n=e.body,l=n?n.length:0;if(1==l)return b(n[0]);for(var t=-1,r="";++t<l;)r+=b(n[t]);return r}function s(e){switch(a(e.type,"anchor"),e.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function i(e){return a(e.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value"),o(e)}function c(e){a(e.type,"characterClass");var n=e.body,l=n?n.length:0,t=-1,r="[";for(e.negative&&(r+="^");++t<l;)r+=f(n[t]);return r+="]"}function d(e){return a(e.type,"characterClassEscape"),"\\"+e.value}function p(e){a(e.type,"characterClassRange");var n=e.min,l=e.max;if("characterClassRange"==n.type||"characterClassRange"==l.type)throw Error("Invalid character class range");return f(n)+"-"+f(l)}function f(e){return a(e.type,"anchor|characterClassEscape|characterClassRange|dot|value"),o(e)}function g(e){a(e.type,"disjunction");var n=e.body,l=n?n.length:0;if(0==l)throw Error("No body");if(1==l)return o(n[0]);for(var t=-1,r="";++t<l;)0!=t&&(r+="|"),r+=o(n[t]);return r}function h(e){return a(e.type,"dot"),"."}function m(e){a(e.type,"group");var n="(";switch(e.behavior){case"normal":break;case"ignore":n+="?:";break;case"lookahead":n+="?=";break;case"negativeLookahead":n+="?!";break;default:throw Error("Invalid behaviour: "+e.behaviour)}var l=e.body,t=l?l.length:0;if(1==t)n+=o(l[0]);else for(var r=-1;++r<t;)n+=o(l[r]);return n+=")"}function y(e){a(e.type,"quantifier");var n="",l=e.min,t=e.max;switch(t){case void 0:case null:switch(l){case 0:n="*";break;case 1:n="+";break;default:n="{"+l+",}"}break;default:n=l==t?"{"+l+"}":0==l&&1==t?"?":"{"+l+","+t+"}"}return e.greedy||(n+="?"),i(e.body[0])+n}function x(e){return a(e.type,"reference"),"\\"+e.matchIndex}function b(e){return a(e.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value"),o(e)}function _(e){a(e.type,"value");var n=e.kind,l=e.codePoint;switch(n){case"controlLetter":return"\\c"+r(l+64);case"hexadecimalEscape":return"\\x"+("00"+l.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+r(l);case"null":return"\\"+l;case"octal":return"\\"+l.toString(8);case"singleEscape":switch(l){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: "+l)}case"symbol":return r(l);case"unicodeEscape":return"\\u"+("0000"+l.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+l.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+n)}}var v={"function":!0,object:!0},I=v[typeof window]&&window||this,E=v[typeof t]&&t,k=v[typeof l]&&l&&!l.nodeType&&l,w=E&&k&&"object"==typeof n&&n;!w||w.global!==w&&w.window!==w&&w.self!==w||(I=w);var R=String.fromCharCode,S=Math.floor;o.alternative=u,o.anchor=s,o.characterClass=c,o.characterClassEscape=d,o.characterClassRange=p,o.disjunction=g,o.dot=h,o.group=m,o.quantifier=y,o.reference=x,o.value=_,"function"==typeof e&&"object"==typeof e.amd&&e.amd?e(function(){return{generate:o}}):E&&k?E.generate=o:I.regjsgen={generate:o}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],298:[function(e,n){!function(){function e(e,n){function l(n){return n.raw=e.substring(n.range[0],n.range[1]),n}function t(e,n){return e.range[0]=n,l(e)}function r(e,n){return l({type:"anchor",kind:e,range:[J-n,J]})}function a(e,n,t,r){return l({type:"value",kind:e,codePoint:n,range:[t,r]})}function o(e,n,l,t){return t=t||0,a(e,n,J-(l.length+t),J)}function u(e){var n=e[0],l=n.charCodeAt(0);if(W){var t;if(1===n.length&&l>=55296&&56319>=l&&(t=v().charCodeAt(0),t>=56320&&57343>=t))return J++,a("symbol",1024*(l-55296)+t-56320+65536,J-2,J)}return a("symbol",l,J-1,J)}function s(e,n,t){return l({type:"disjunction",body:e,range:[n,t]})}function i(){return l({type:"dot",range:[J-1,J]})}function c(e){return l({type:"characterClassEscape",value:e,range:[J-2,J]})}function d(e){return l({type:"reference",matchIndex:parseInt(e,10),range:[J-1-e.length,J]})}function p(e,n,t,r){return l({type:"group",behavior:e,body:n,range:[t,r]})}function f(e,n,t,r){return null==r&&(t=J-1,r=J),l({type:"quantifier",min:e,max:n,greedy:!0,body:null,range:[t,r]})}function g(e,n,t){return l({type:"alternative",body:e,range:[n,t]})}function h(e,n,t,r){return l({type:"characterClass",body:e,negative:n,range:[t,r]})}function m(e,n,t,r){if(e.codePoint>n.codePoint)throw SyntaxError("invalid range in character class");return l({type:"characterClassRange",min:e,max:n,range:[t,r]})}function y(e){return"alternative"===e.type?e.body:[e]}function x(n){n=n||1;var l=e.substring(J,J+n);return J+=n||1,l}function b(e){if(!_(e))throw SyntaxError("character: "+e)}function _(n){return e.indexOf(n,J)===J?x(n.length):void 0}function v(){return e[J]}function I(n){return e.indexOf(n,J)===J}function E(n){return e[J+1]===n}function k(n){var l=e.substring(J),t=l.match(n);return t&&(t.range=[],t.range[0]=J,x(t[0].length),t.range[1]=J),t}function w(){var e=[],n=J;for(e.push(R());_("|");)e.push(R());return 1===e.length?e[0]:s(e,n,J)}function R(){for(var e,n=[],l=J;e=S();)n.push(e);return 1===n.length?n[0]:g(n,l,J)}function S(){if(J>=e.length||I("|")||I(")"))return null;var n=A();if(n)return n;var l=T();if(!l)throw SyntaxError("Expected atom");var r=j()||!1;return r?(r.body=y(l),t(r,l.range[0]),r):l}function C(e,n,l,t){var r=null,a=J;if(_(e))r=n;else{if(!_(l))return!1;r=t}var o=w();if(!o)throw SyntaxError("Expected disjunction");b(")");var u=p(r,y(o),a,J);return"normal"==r&&Y++,u}function A(){return _("^")?r("start",1):_("$")?r("end",1):_("\\b")?r("boundary",2):_("\\B")?r("not-boundary",2):C("(?=","lookahead","(?!","negativeLookahead")}function j(){var e,n,l,t;if(_("*"))n=f(0);else if(_("+"))n=f(1);else if(_("?"))n=f(0,1);else if(e=k(/^\{([0-9]+)\}/))l=parseInt(e[1],10),n=f(l,l,e.range[0],e.range[1]);else if(e=k(/^\{([0-9]+),\}/))l=parseInt(e[1],10),n=f(l,void 0,e.range[0],e.range[1]);else if(e=k(/^\{([0-9]+),([0-9]+)\}/)){if(l=parseInt(e[1],10),t=parseInt(e[2],10),l>t)throw SyntaxError("numbers out of order in {} quantifier");n=f(l,t,e.range[0],e.range[1])}return n&&_("?")&&(n.greedy=!1,n.range[1]+=1),n}function T(){var e;if(e=k(/^[^^$\\.*+?(){[|]/))return u(e);if(_("."))return i();if(_("\\")){if(e=O(),!e)throw SyntaxError("atomEscape");return e}return(e=F())?e:C("(?:","ignore","(","normal")
}function L(e){if(W){var n,t;if("unicodeEscape"==e.kind&&(n=e.codePoint)>=55296&&56319>=n&&I("\\")&&E("u")){var r=J;J++;var a=P();"unicodeEscape"==a.kind&&(t=a.codePoint)>=56320&&57343>=t?(e.range[1]=a.range[1],e.codePoint=1024*(n-55296)+t-56320+65536,e.type="value",e.kind="unicodeCodePointEscape",l(e)):J=r}}return e}function P(){return O(!0)}function O(e){var n;if(n=M())return n;if(e){if(_("b"))return o("singleEscape",8,"\\b");if(_("B"))throw SyntaxError("\\B not possible inside of CharacterClass")}return n=D()}function M(){var e,n;if(e=k(/^(?!0)\d+/)){n=e[0];var l=parseInt(e[0],10);return Y>=l?d(e[0]):(x(-e[0].length),(e=k(/^[0-7]{1,3}/))?o("octal",parseInt(e[0],8),e[0],1):(e=u(k(/^[89]/)),t(e,e.range[0]-1)))}return(e=k(/^[0-7]{1,3}/))?(n=e[0],/^0{1,3}$/.test(n)?o("null",0,"0",n.length+1):o("octal",parseInt(n,8),n,1)):(e=k(/^[dDsSwW]/))?c(e[0]):!1}function D(){var e;if(e=k(/^[fnrtv]/)){var n=0;switch(e[0]){case"t":n=9;break;case"n":n=10;break;case"v":n=11;break;case"f":n=12;break;case"r":n=13}return o("singleEscape",n,"\\"+e[0])}return(e=k(/^c([a-zA-Z])/))?o("controlLetter",e[1].charCodeAt(0)%32,e[1],2):(e=k(/^x([0-9a-fA-F]{2})/))?o("hexadecimalEscape",parseInt(e[1],16),e[1],2):(e=k(/^u([0-9a-fA-F]{4})/))?L(o("unicodeEscape",parseInt(e[1],16),e[1],2)):W&&(e=k(/^u\{([0-9a-fA-F]{1,})\}/))?o("unicodeCodePointEscape",parseInt(e[1],16),e[1],4):B()}function N(e){var n=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return 36===e||95===e||e>=65&&90>=e||e>=97&&122>=e||e>=48&&57>=e||92===e||e>=128&&n.test(String.fromCharCode(e))}function B(){var e,n="",l="";return N(v())?_(n)?o("identifier",8204,n):_(l)?o("identifier",8205,l):null:(e=x(),o("identifier",e.charCodeAt(0),e,1))}function F(){var e,n=J;return(e=k(/^\[\^/))?(e=V(),b("]"),h(e,!0,n,J)):_("[")?(e=V(),b("]"),h(e,!1,n,J)):null}function V(){var e;if(I("]"))return[];if(e=q(),!e)throw SyntaxError("nonEmptyClassRanges");return e}function U(e){var n,l,t;if(I("-")&&!E("]")){if(b("-"),t=H(),!t)throw SyntaxError("classAtom");l=J;var r=V();if(!r)throw SyntaxError("classRanges");return n=e.range[0],"empty"===r.type?[m(e,t,n,l)]:[m(e,t,n,l)].concat(r)}if(t=G(),!t)throw SyntaxError("nonEmptyClassRangesNoDash");return[e].concat(t)}function q(){var e=H();if(!e)throw SyntaxError("classAtom");return I("]")?[e]:U(e)}function G(){var e=H();if(!e)throw SyntaxError("classAtom");return I("]")?e:U(e)}function H(){return _("-")?u("-"):X()}function X(){var e;if(e=k(/^[^\\\]-]/))return u(e[0]);if(_("\\")){if(e=P(),!e)throw SyntaxError("classEscape");return L(e)}}var W=-1!==(n||"").indexOf("u"),J=0,Y=0;e=String(e),""===e&&(e="(?:)");var z=w();if(z.range[1]!==e.length)throw SyntaxError("Could not parse entire input - got stuck: "+e);return z}var l={parse:e};"undefined"!=typeof n&&n.exports?n.exports=l:window.regjsparser=l}()},{}],299:[function(e,n){function l(e){return I?v?g.UNICODE_IGNORE_CASE[e]:g.UNICODE[e]:g.REGULAR[e]}function t(e,n){return m.call(e,n)}function r(e,n){for(var l in n)e[l]=n[l]}function a(e,n){if(n){var l=d(n,"");switch(l.type){case"characterClass":case"group":case"value":break;default:l=o(l,n)}r(e,l)}}function o(e,n){return{type:"group",behavior:"ignore",body:[e],raw:"(?:"+n+")"}}function u(e){return t(f,e)?f[e]:!1}function s(e){{var n=p();e.body.forEach(function(e){switch(e.type){case"value":if(n.add(e.codePoint),v&&I){var t=u(e.codePoint);t&&n.add(t)}break;case"characterClassRange":var r=e.min.codePoint,a=e.max.codePoint;n.addRange(r,a),v&&I&&n.iuAddRange(r,a);break;case"characterClassEscape":n.add(l(e.value));break;default:throw Error("Unknown term type: "+e.type)}})}return e.negative&&(n=(I?y:x).clone().remove(n)),a(e,n.toString()),e}function i(e){switch(e.type){case"dot":a(e,(I?b:_).toString());break;case"characterClass":e=s(e);break;case"characterClassEscape":a(e,l(e.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":e.body=e.body.map(i);break;case"value":var n=e.codePoint,t=p(n);if(v&&I){var r=u(n);r&&t.add(r)}a(e,t.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+e.type)}return e}var c=e("regjsgen").generate,d=e("regjsparser").parse,p=e("regenerate"),f=e("./data/iu-mappings.json"),g=e("./data/character-class-escape-sets.js"),h={},m=h.hasOwnProperty,y=p().addRange(0,1114111),x=p().addRange(0,65535),b=y.clone().remove(10,13,8232,8233),_=b.clone().intersection(x);p.prototype.iuAddRange=function(e,n){var l=this;do{var t=u(e);t&&l.add(t)}while(++e<=n);return l};var v=!1,I=!1;n.exports=function(e,n){var l=d(e,n);return v=n?n.indexOf("i")>-1:!1,I=n?n.indexOf("u")>-1:!1,r(l,i(l)),c(l)}},{"./data/character-class-escape-sets.js":294,"./data/iu-mappings.json":295,regenerate:296,regjsgen:297,regjsparser:298}],300:[function(e,n){"use strict";var l=e("is-finite");n.exports=function(e,n){if("string"!=typeof e)throw new TypeError("Expected a string as the first argument");if(0>n||!l(n))throw new TypeError("Expected a finite positive number");var t="";do 1&n&&(t+=e),e+=e;while(n>>=1);return t}},{"is-finite":301}],301:[function(e,n,l){arguments[4][183][0].apply(l,arguments)},{dup:183}],302:[function(e,n){"use strict";n.exports=/^#!.*/},{}],303:[function(e,n){"use strict";n.exports=function(e){var n=/^\\\\\?\\/.test(e),l=/[^\x00-\x80]+/.test(e);return n||l?e:e.replace(/\\/g,"/")}},{}],304:[function(e,n){(function(e){"use strict";n.exports=function(n){var l=new e(JSON.stringify(n)).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+l}}).call(this,e("buffer").Buffer)},{buffer:137}],305:[function(e,n,l){l.SourceMapGenerator=e("./source-map/source-map-generator").SourceMapGenerator,l.SourceMapConsumer=e("./source-map/source-map-consumer").SourceMapConsumer,l.SourceNode=e("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":311,"./source-map/source-map-generator":312,"./source-map/source-node":313}],306:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){function l(){this._array=[],this._set={}}var t=e("./util");l.fromArray=function(e,n){for(var t=new l,r=0,a=e.length;a>r;r++)t.add(e[r],n);return t},l.prototype.add=function(e,n){var l=this.has(e),r=this._array.length;(!l||n)&&this._array.push(e),l||(this._set[t.toSetString(e)]=r)},l.prototype.has=function(e){return Object.prototype.hasOwnProperty.call(this._set,t.toSetString(e))},l.prototype.indexOf=function(e){if(this.has(e))return this._set[t.toSetString(e)];throw new Error('"'+e+'" is not in the set.')},l.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw new Error("No element indexed by "+e)},l.prototype.toArray=function(){return this._array.slice()},n.ArraySet=l})},{"./util":314,amdefine:315}],307:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){function l(e){return 0>e?(-e<<1)+1:(e<<1)+0}function t(e){var n=1===(1&e),l=e>>1;return n?-l:l}var r=e("./base64"),a=5,o=1<<a,u=o-1,s=o;n.encode=function(e){var n,t="",o=l(e);do n=o&u,o>>>=a,o>0&&(n|=s),t+=r.encode(n);while(o>0);return t},n.decode=function(e,n){var l,o,i=0,c=e.length,d=0,p=0;do{if(i>=c)throw new Error("Expected more digits in base 64 VLQ value.");o=r.decode(e.charAt(i++)),l=!!(o&s),o&=u,d+=o<<p,p+=a}while(l);n.value=t(d),n.rest=e.slice(i)}})},{"./base64":308,amdefine:315}],308:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){var l={},t={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(e,n){l[e]=n,t[n]=e}),n.encode=function(e){if(e in t)return t[e];throw new TypeError("Must be between 0 and 63: "+e)},n.decode=function(e){if(e in l)return l[e];throw new TypeError("Not a valid base 64 digit: "+e)}})},{amdefine:315}],309:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){function l(e,n,t,r,a){var o=Math.floor((n-e)/2)+e,u=a(t,r[o],!0);return 0===u?o:u>0?n-o>1?l(o,n,t,r,a):o:o-e>1?l(e,o,t,r,a):0>e?-1:e}n.search=function(e,n,t){return 0===n.length?-1:l(-1,n.length,e,n,t)}})},{amdefine:315}],310:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){function l(e,n){var l=e.generatedLine,t=n.generatedLine,a=e.generatedColumn,o=n.generatedColumn;return t>l||t==l&&o>=a||r.compareByGeneratedPositions(e,n)<=0}function t(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var r=e("./util");t.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},t.prototype.add=function(e){l(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},t.prototype.toArray=function(){return this._sorted||(this._array.sort(r.compareByGeneratedPositions),this._sorted=!0),this._array},n.MappingList=t})},{"./util":314,amdefine:315}],311:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){function l(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var l=t.getArg(n,"version"),r=t.getArg(n,"sources"),o=t.getArg(n,"names",[]),u=t.getArg(n,"sourceRoot",null),s=t.getArg(n,"sourcesContent",null),i=t.getArg(n,"mappings"),c=t.getArg(n,"file",null);if(l!=this._version)throw new Error("Unsupported version: "+l);r=r.map(t.normalize),this._names=a.fromArray(o,!0),this._sources=a.fromArray(r,!0),this.sourceRoot=u,this.sourcesContent=s,this._mappings=i,this.file=c}var t=e("./util"),r=e("./binary-search"),a=e("./array-set").ArraySet,o=e("./base64-vlq");l.fromSourceMap=function(e){var n=Object.create(l.prototype);return n._names=a.fromArray(e._names.toArray(),!0),n._sources=a.fromArray(e._sources.toArray(),!0),n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file,n.__generatedMappings=e._mappings.toArray().slice(),n.__originalMappings=e._mappings.toArray().slice().sort(t.compareByOriginalPositions),n},l.prototype._version=3,Object.defineProperty(l.prototype,"sources",{get:function(){return this._sources.toArray().map(function(e){return null!=this.sourceRoot?t.join(this.sourceRoot,e):e},this)}}),l.prototype.__generatedMappings=null,Object.defineProperty(l.prototype,"_generatedMappings",{get:function(){return this.__generatedMappings||(this.__generatedMappings=[],this.__originalMappings=[],this._parseMappings(this._mappings,this.sourceRoot)),this.__generatedMappings}}),l.prototype.__originalMappings=null,Object.defineProperty(l.prototype,"_originalMappings",{get:function(){return this.__originalMappings||(this.__generatedMappings=[],this.__originalMappings=[],this._parseMappings(this._mappings,this.sourceRoot)),this.__originalMappings}}),l.prototype._nextCharIsMappingSeparator=function(e){var n=e.charAt(0);return";"===n||","===n},l.prototype._parseMappings=function(e){for(var n,l=1,r=0,a=0,u=0,s=0,i=0,c=e,d={};c.length>0;)if(";"===c.charAt(0))l++,c=c.slice(1),r=0;else if(","===c.charAt(0))c=c.slice(1);else{if(n={},n.generatedLine=l,o.decode(c,d),n.generatedColumn=r+d.value,r=n.generatedColumn,c=d.rest,c.length>0&&!this._nextCharIsMappingSeparator(c)){if(o.decode(c,d),n.source=this._sources.at(s+d.value),s+=d.value,c=d.rest,0===c.length||this._nextCharIsMappingSeparator(c))throw new Error("Found a source, but no line and column");if(o.decode(c,d),n.originalLine=a+d.value,a=n.originalLine,n.originalLine+=1,c=d.rest,0===c.length||this._nextCharIsMappingSeparator(c))throw new Error("Found a source and line, but no column");o.decode(c,d),n.originalColumn=u+d.value,u=n.originalColumn,c=d.rest,c.length>0&&!this._nextCharIsMappingSeparator(c)&&(o.decode(c,d),n.name=this._names.at(i+d.value),i+=d.value,c=d.rest)}this.__generatedMappings.push(n),"number"==typeof n.originalLine&&this.__originalMappings.push(n)}this.__generatedMappings.sort(t.compareByGeneratedPositions),this.__originalMappings.sort(t.compareByOriginalPositions)},l.prototype._findMapping=function(e,n,l,t,a){if(e[l]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[l]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return r.search(e,n,a)},l.prototype.computeColumnSpans=function(){for(var e=0;e<this._generatedMappings.length;++e){var n=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var l=this._generatedMappings[e+1];if(n.generatedLine===l.generatedLine){n.lastGeneratedColumn=l.generatedColumn-1;continue}}n.lastGeneratedColumn=1/0}},l.prototype.originalPositionFor=function(e){var n={generatedLine:t.getArg(e,"line"),generatedColumn:t.getArg(e,"column")},l=this._findMapping(n,this._generatedMappings,"generatedLine","generatedColumn",t.compareByGeneratedPositions);if(l>=0){var r=this._generatedMappings[l];if(r.generatedLine===n.generatedLine){var a=t.getArg(r,"source",null);return null!=a&&null!=this.sourceRoot&&(a=t.join(this.sourceRoot,a)),{source:a,line:t.getArg(r,"originalLine",null),column:t.getArg(r,"originalColumn",null),name:t.getArg(r,"name",null)}}}return{source:null,line:null,column:null,name:null}},l.prototype.sourceContentFor=function(e){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=t.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var n;if(null!=this.sourceRoot&&(n=t.urlParse(this.sourceRoot))){var l=e.replace(/^file:\/\//,"");if("file"==n.scheme&&this._sources.has(l))return this.sourcesContent[this._sources.indexOf(l)];if((!n.path||"/"==n.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}throw new Error('"'+e+'" is not in the SourceMap.')},l.prototype.generatedPositionFor=function(e){var n={source:t.getArg(e,"source"),originalLine:t.getArg(e,"line"),originalColumn:t.getArg(e,"column")};null!=this.sourceRoot&&(n.source=t.relative(this.sourceRoot,n.source));var l=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",t.compareByOriginalPositions);if(l>=0){var r=this._originalMappings[l];return{line:t.getArg(r,"generatedLine",null),column:t.getArg(r,"generatedColumn",null),lastColumn:t.getArg(r,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},l.prototype.allGeneratedPositionsFor=function(e){var n={source:t.getArg(e,"source"),originalLine:t.getArg(e,"line"),originalColumn:1/0};null!=this.sourceRoot&&(n.source=t.relative(this.sourceRoot,n.source));var l=[],r=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",t.compareByOriginalPositions);if(r>=0)for(var a=this._originalMappings[r];a&&a.originalLine===n.originalLine;)l.push({line:t.getArg(a,"generatedLine",null),column:t.getArg(a,"generatedColumn",null),lastColumn:t.getArg(a,"lastGeneratedColumn",null)}),a=this._originalMappings[--r];return l.reverse()},l.GENERATED_ORDER=1,l.ORIGINAL_ORDER=2,l.prototype.eachMapping=function(e,n,r){var a,o=n||null,u=r||l.GENERATED_ORDER;switch(u){case l.GENERATED_ORDER:a=this._generatedMappings;break;case l.ORIGINAL_ORDER:a=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var s=this.sourceRoot;a.map(function(e){var n=e.source;return null!=n&&null!=s&&(n=t.join(s,n)),{source:n,generatedLine:e.generatedLine,generatedColumn:e.generatedColumn,originalLine:e.originalLine,originalColumn:e.originalColumn,name:e.name}}).forEach(e,o)},n.SourceMapConsumer=l})},{"./array-set":306,"./base64-vlq":307,"./binary-search":309,"./util":314,amdefine:315}],312:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){function l(e){e||(e={}),this._file=r.getArg(e,"file",null),this._sourceRoot=r.getArg(e,"sourceRoot",null),this._skipValidation=r.getArg(e,"skipValidation",!1),this._sources=new a,this._names=new a,this._mappings=new o,this._sourcesContents=null}var t=e("./base64-vlq"),r=e("./util"),a=e("./array-set").ArraySet,o=e("./mapping-list").MappingList;l.prototype._version=3,l.fromSourceMap=function(e){var n=e.sourceRoot,t=new l({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var l={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(l.source=e.source,null!=n&&(l.source=r.relative(n,l.source)),l.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(l.name=e.name)),t.addMapping(l)}),e.sources.forEach(function(n){var l=e.sourceContentFor(n);null!=l&&t.setSourceContent(n,l)}),t},l.prototype.addMapping=function(e){var n=r.getArg(e,"generated"),l=r.getArg(e,"original",null),t=r.getArg(e,"source",null),a=r.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,l,t,a),null==t||this._sources.has(t)||this._sources.add(t),null==a||this._names.has(a)||this._names.add(a),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=l&&l.line,originalColumn:null!=l&&l.column,source:t,name:a})},l.prototype.setSourceContent=function(e,n){var l=e;null!=this._sourceRoot&&(l=r.relative(this._sourceRoot,l)),null!=n?(this._sourcesContents||(this._sourcesContents={}),this._sourcesContents[r.toSetString(l)]=n):this._sourcesContents&&(delete this._sourcesContents[r.toSetString(l)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},l.prototype.applySourceMap=function(e,n,l){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=r.relative(o,t));var u=new a,s=new a;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var a=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=a.source&&(n.source=a.source,null!=l&&(n.source=r.join(l,n.source)),null!=o&&(n.source=r.relative(o,n.source)),n.originalLine=a.line,n.originalColumn=a.column,null!=a.name&&(n.name=a.name))}var i=n.source;null==i||u.has(i)||u.add(i);var c=n.name;null==c||s.has(c)||s.add(c)},this),this._sources=u,this._names=s,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=l&&(n=r.join(l,n)),null!=o&&(n=r.relative(o,n)),this.setSourceContent(n,t))},this)},l.prototype._validateMapping=function(e,n,l,t){if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!n&&!l&&!t||e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&l))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:l,original:n,name:t}))},l.prototype._serializeMappings=function(){for(var e,n=0,l=1,a=0,o=0,u=0,s=0,i="",c=this._mappings.toArray(),d=0,p=c.length;p>d;d++){if(e=c[d],e.generatedLine!==l)for(n=0;e.generatedLine!==l;)i+=";",l++;else if(d>0){if(!r.compareByGeneratedPositions(e,c[d-1]))continue;i+=","}i+=t.encode(e.generatedColumn-n),n=e.generatedColumn,null!=e.source&&(i+=t.encode(this._sources.indexOf(e.source)-s),s=this._sources.indexOf(e.source),i+=t.encode(e.originalLine-1-o),o=e.originalLine-1,i+=t.encode(e.originalColumn-a),a=e.originalColumn,null!=e.name&&(i+=t.encode(this._names.indexOf(e.name)-u),u=this._names.indexOf(e.name)))}return i},l.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=r.relative(n,e));var l=r.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,l)?this._sourcesContents[l]:null},this)},l.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},l.prototype.toString=function(){return JSON.stringify(this)},n.SourceMapGenerator=l})},{"./array-set":306,"./base64-vlq":307,"./mapping-list":310,"./util":314,amdefine:315}],313:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){function l(e,n,l,t,r){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==n?null:n,this.source=null==l?null:l,this.name=null==r?null:r,this[u]=!0,null!=t&&this.add(t)}var t=e("./source-map-generator").SourceMapGenerator,r=e("./util"),a=/(\r?\n)/,o=10,u="$$$isSourceNode$$$";l.fromStringWithSourceMap=function(e,n,t){function o(e,n){if(null===e||void 0===e.source)u.add(n);else{var a=t?r.join(t,e.source):e.source;u.add(new l(e.originalLine,e.originalColumn,a,n,e.name))}}var u=new l,s=e.split(a),i=function(){var e=s.shift(),n=s.shift()||"";return e+n},c=1,d=0,p=null;return n.eachMapping(function(e){if(null!==p){if(!(c<e.generatedLine)){var n=s[0],l=n.substr(0,e.generatedColumn-d);return s[0]=n.substr(e.generatedColumn-d),d=e.generatedColumn,o(p,l),void(p=e)}var l="";o(p,i()),c++,d=0}for(;c<e.generatedLine;)u.add(i()),c++;if(d<e.generatedColumn){var n=s[0];u.add(n.substr(0,e.generatedColumn)),s[0]=n.substr(e.generatedColumn),d=e.generatedColumn}p=e},this),s.length>0&&(p&&o(p,i()),u.add(s.join(""))),n.sources.forEach(function(e){var l=n.sourceContentFor(e);null!=l&&(null!=t&&(e=r.join(t,e)),u.setSourceContent(e,l))}),u},l.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);e&&this.children.push(e)}return this},l.prototype.prepend=function(e){if(Array.isArray(e))for(var n=e.length-1;n>=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},l.prototype.walk=function(e){for(var n,l=0,t=this.children.length;t>l;l++)n=this.children[l],n[u]?n.walk(e):""!==n&&e(n,{source:this.source,line:this.line,column:this.column,name:this.name})},l.prototype.join=function(e){var n,l,t=this.children.length;if(t>0){for(n=[],l=0;t-1>l;l++)n.push(this.children[l]),n.push(e);n.push(this.children[l]),this.children=n}return this},l.prototype.replaceRight=function(e,n){var l=this.children[this.children.length-1];return l[u]?l.replaceRight(e,n):"string"==typeof l?this.children[this.children.length-1]=l.replace(e,n):this.children.push("".replace(e,n)),this},l.prototype.setSourceContent=function(e,n){this.sourceContents[r.toSetString(e)]=n},l.prototype.walkSourceContents=function(e){for(var n=0,l=this.children.length;l>n;n++)this.children[n][u]&&this.children[n].walkSourceContents(e);for(var t=Object.keys(this.sourceContents),n=0,l=t.length;l>n;n++)e(r.fromSetString(t[n]),this.sourceContents[t[n]])},l.prototype.toString=function(){var e="";return this.walk(function(n){e+=n}),e},l.prototype.toStringWithSourceMap=function(e){var n={code:"",line:1,column:0},l=new t(e),r=!1,a=null,u=null,s=null,i=null;return this.walk(function(e,t){n.code+=e,null!==t.source&&null!==t.line&&null!==t.column?((a!==t.source||u!==t.line||s!==t.column||i!==t.name)&&l.addMapping({source:t.source,original:{line:t.line,column:t.column},generated:{line:n.line,column:n.column},name:t.name}),a=t.source,u=t.line,s=t.column,i=t.name,r=!0):r&&(l.addMapping({generated:{line:n.line,column:n.column}}),a=null,r=!1);for(var c=0,d=e.length;d>c;c++)e.charCodeAt(c)===o?(n.line++,n.column=0,c+1===d?(a=null,r=!1):r&&l.addMapping({source:t.source,original:{line:t.line,column:t.column},generated:{line:n.line,column:n.column},name:t.name})):n.column++}),this.walkSourceContents(function(e,n){l.setSourceContent(e,n)}),{code:n.code,map:l}},n.SourceNode=l})},{"./source-map-generator":312,"./util":314,amdefine:315}],314:[function(e,n){if("function"!=typeof l)var l=e("amdefine")(n,e);l(function(e,n){function l(e,n,l){if(n in e)return e[n];if(3===arguments.length)return l;throw new Error('"'+n+'" is a required argument.')}function t(e){var n=e.match(f);return n?{scheme:n[1],auth:n[2],host:n[3],port:n[4],path:n[5]}:null}function r(e){var n="";return e.scheme&&(n+=e.scheme+":"),n+="//",e.auth&&(n+=e.auth+"@"),e.host&&(n+=e.host),e.port&&(n+=":"+e.port),e.path&&(n+=e.path),n}function a(e){var n=e,l=t(e);if(l){if(!l.path)return e;n=l.path}for(var a,o="/"===n.charAt(0),u=n.split(/\/+/),s=0,i=u.length-1;i>=0;i--)a=u[i],"."===a?u.splice(i,1):".."===a?s++:s>0&&(""===a?(u.splice(i+1,s),s=0):(u.splice(i,2),s--));return n=u.join("/"),""===n&&(n=o?"/":"."),l?(l.path=n,r(l)):n}function o(e,n){""===e&&(e="."),""===n&&(n=".");var l=t(n),o=t(e);if(o&&(e=o.path||"/"),l&&!l.scheme)return o&&(l.scheme=o.scheme),r(l);if(l||n.match(g))return n;if(o&&!o.host&&!o.path)return o.host=n,r(o);var u="/"===n.charAt(0)?n:a(e.replace(/\/+$/,"")+"/"+n);return o?(o.path=u,r(o)):u}function u(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");var l=t(e);return"/"==n.charAt(0)&&l&&"/"==l.path?n.slice(1):0===n.indexOf(e+"/")?n.substr(e.length+1):n}function s(e){return"$"+e}function i(e){return e.substr(1)}function c(e,n){var l=e||"",t=n||"";return(l>t)-(t>l)}function d(e,n,l){var t;return(t=c(e.source,n.source))?t:(t=e.originalLine-n.originalLine)?t:(t=e.originalColumn-n.originalColumn,t||l?t:(t=c(e.name,n.name))?t:(t=e.generatedLine-n.generatedLine,t?t:e.generatedColumn-n.generatedColumn))}function p(e,n,l){var t;return(t=e.generatedLine-n.generatedLine)?t:(t=e.generatedColumn-n.generatedColumn,t||l?t:(t=c(e.source,n.source))?t:(t=e.originalLine-n.originalLine)?t:(t=e.originalColumn-n.originalColumn,t?t:c(e.name,n.name)))}n.getArg=l;var f=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,g=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=r,n.normalize=a,n.join=o,n.relative=u,n.toSetString=s,n.fromSetString=i,n.compareByOriginalPositions=d,n.compareByGeneratedPositions=p})},{amdefine:315}],315:[function(e,n){(function(l,t){"use strict";function r(n,r){function a(e){var n,l;for(n=0;e[n];n+=1)if(l=e[n],"."===l)e.splice(n,1),n-=1;else if(".."===l){if(1===n&&(".."===e[2]||".."===e[0]))break;n>0&&(e.splice(n-1,2),n-=2)}}function o(e,n){var l;return e&&"."===e.charAt(0)&&n&&(l=n.split("/"),l=l.slice(0,l.length-1),l=l.concat(e.split("/")),a(l),e=l.join("/")),e}function u(e){return function(n){return o(n,e)}}function s(e){function n(n){g[e]=n}return n.fromText=function(){throw new Error("amdefine does not implement load.fromText")},n}function i(e,l,a){var o,u,s,i;if(e)u=g[e]={},s={id:e,uri:t,exports:u},o=d(r,u,s,e);else{if(h)throw new Error("amdefine with no module ID cannot be called more than once per file.");h=!0,u=n.exports,s=n,o=d(r,u,s,n.id)}l&&(l=l.map(function(e){return o(e)})),i="function"==typeof a?a.apply(s.exports,l):a,void 0!==i&&(s.exports=i,e&&(g[e]=s.exports))}function c(e,n,l){Array.isArray(e)?(l=n,n=e,e=void 0):"string"!=typeof e&&(l=e,e=n=void 0),n&&!Array.isArray(n)&&(l=n,n=void 0),n||(n=["require","exports","module"]),e?f[e]=[e,n,l]:i(e,n,l)}var d,p,f={},g={},h=!1,m=e("path");return d=function(e,n,t,r){function a(a,o){return"string"==typeof a?p(e,n,t,a,r):(a=a.map(function(l){return p(e,n,t,l,r)}),void l.nextTick(function(){o.apply(null,a)}))}return a.toUrl=function(e){return 0===e.indexOf(".")?o(e,m.dirname(t.filename)):e},a},r=r||function(){return n.require.apply(n,arguments)},p=function(e,n,l,t,r){var a,c,h=t.indexOf("!"),m=t;if(-1===h){if(t=o(t,r),"require"===t)return d(e,n,l,r);if("exports"===t)return n;if("module"===t)return l;if(g.hasOwnProperty(t))return g[t];if(f[t])return i.apply(null,f[t]),g[t];if(e)return e(m);throw new Error("No module with ID: "+t)}return a=t.substring(0,h),t=t.substring(h+1,t.length),c=p(e,n,l,a,r),t=c.normalize?c.normalize(t,u(r)):o(t,r),g[t]?g[t]:(c.load(t,d(e,n,l,r),s(t),{}),g[t])},c.require=function(e){return g[e]?g[e]:f[e]?(i.apply(null,f[e]),g[e]):void 0},c.amd={},c}n.exports=r}).call(this,e("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:145,path:144}],316:[function(e,n){"use strict";n.exports=function(e){return e.replace(/[\s\uFEFF\xA0]+$/g,"")}},{}],317:[function(e,n){n.exports={name:"babel",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"4.4.1",author:"Sebastian McKenzie <[email protected]>",homepage:"https://babeljs.io/",repository:"babel/babel",preferGlobal:!0,main:"lib/babel/api/node.js",browser:{"./lib/babel/api/register/node.js":"./lib/babel/api/register/browser.js"},bin:{"6to5":"./bin/deprecated/6to5","6to5-node":"./bin/deprecated/6to5-node","6to5-runtime":"./bin/deprecated/6to5-runtime",babel:"./bin/babel/index.js","babel-node":"./bin/babel-node","babel-external-helpers":"./bin/babel-external-helpers"},keywords:["harmony","classes","modules","let","const","var","es6","transpile","transpiler","6to5","babel"],scripts:{bench:"make bench",test:"make test"},dependencies:{"acorn-babel":"0.11.1-33","ast-types":"~0.6.1",chalk:"^0.5.1",chokidar:"^0.12.6",commander:"^2.6.0","core-js":"^0.5.4",debug:"^2.1.1","detect-indent":"^3.0.0",estraverse:"^1.9.1",esutils:"^1.1.6","fs-readdir-recursive":"^0.1.0",globals:"^6.2.0","is-integer":"^1.0.4","js-tokenizer":"^1.3.3",leven:"^1.0.1",lodash:"^3.2.0","output-file-sync":"^1.1.0","path-is-absolute":"^1.0.0","private":"^0.1.6","regenerator-babel":"0.8.10-2",regexpu:"^1.1.1",repeating:"^1.1.2","shebang-regex":"^1.0.0",slash:"^1.0.0","source-map":"^0.1.43","source-map-support":"^0.2.9","source-map-to-comment":"^1.0.0","trim-right":"^1.0.0"},devDependencies:{browserify:"^8.1.3",chai:"^2.0.0",esvalid:"^1.1.0",istanbul:"^0.3.5",jscs:"^1.11.3",jshint:"^2.6.0","jshint-stylish":"^1.0.0",matcha:"^0.6.0",mocha:"^2.1.0",rimraf:"^2.2.8","uglify-js":"^2.4.16"}}},{}],318:[function(e,n){n.exports={"abstract-expression-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-delete":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceDelete",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-get":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-set":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceSet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"apply-constructor":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-comprehension-container":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-from":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-push":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STATEMENT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"async-to-generator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"next",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"throw",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionDeclaration",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"TryStatement",start:null,end:null,loc:null,range:null,block:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},handler:{type:"CatchClause",start:null,end:null,loc:null,range:null,param:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},guard:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},guardedHandlers:[],finalizer:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"then",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},bind:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Function",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},call:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CONTEXT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-call-check":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:!0,argument:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"instanceof",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:"Cannot call a class as a function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"corejs-is-iterator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CORE_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"$for",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isIterable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"corejs-iterator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CORE_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"$for",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getIterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"default-parameter":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"DEFAULT_VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"let",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},defaults:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyNames",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:!1,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"define-property":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-default-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-module-declaration-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-module-declaration":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"__esModule",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"extends":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"assign",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:1,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:!1,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:null,update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:!1,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:!0,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},get:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"has-own":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},inherits:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"Super expression must either be null or a function, not ",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"+",right:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:!1,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__proto__",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require-wildcard":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"let-scoping-return":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"v",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"named-func":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"FunctionDeclaration",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"GET_OUTER_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:!1,expression:!1,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"object-destructuring-empty":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:"Cannot destructure undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"object-without-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"indexOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:!0,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"property-method-assignment-wrapper-generator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:!0,expression:!1,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"YieldExpression",start:null,end:null,loc:null,range:null,delegate:!0,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"property-method-assignment-wrapper":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:!1,expression:!1,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-identifier":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"require-assign-key":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},require:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},rest:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"START",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:!1,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"self-contained-helpers-head":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"helpers",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"self-global":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"self",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},set:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},slice:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"slice",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"sliced-to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"in",right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:!0,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:"Invalid attempt to destructure non-iterable instance",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},system:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"System",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"register",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_DEPENDENCIES",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXPORT_IDENTIFIER",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setters",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SETTERS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"execute",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXECUTE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tail-call-body":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"AGAIN_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"LabeledStatement",start:null,end:null,loc:null,range:null,body:{type:"WhileStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"AGAIN_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"BLOCK",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},label:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"temporal-assert-defined":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"val",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"name",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undef",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"val",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undef",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ReferenceError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"name",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"+",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:" is not defined - temporal dead zone",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Literal",start:null,end:null,loc:null,range:null,value:!0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"temporal-undefined":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-exports":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-module":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"to-consumable-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr2",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:!1,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr2",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!0,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr2",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"typeof":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Literal",start:null,end:null,loc:null,range:null,value:"symbol",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},alternate:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"umd-runner-body":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"amd",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:!1,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"AMD_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_TEST",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}}
},{}]},{},[1])(1)}); |
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js | fengshao0907/actor-platform | import _ from 'lodash';
import Immutable from 'immutable';
import keymirror from 'keymirror';
import React from 'react';
import { Styles, TextField, FlatButton } from 'material-ui';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import ContactStore from 'stores/ContactStore';
import ContactItem from './ContactItem.react';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const STEPS = keymirror({
NAME_INPUT: null,
CONTACTS_SELECTION: null
});
class CreateGroupForm extends React.Component {
static displayName = 'CreateGroupForm'
static childContextTypes = {
muiTheme: React.PropTypes.object
};
state = {
step: STEPS.NAME_INPUT,
selectedUserIds: new Immutable.Set()
}
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7'
}
});
}
render() {
let stepForm;
switch (this.state.step) {
case STEPS.NAME_INPUT:
stepForm = (
<form className="group-name" onSubmit={this.onNameSubmit}>
<div className="modal-new__body">
<TextField className="login__form__input"
floatingLabelText="Group name"
fullWidth
onChange={this.onNameChange}
value={this.state.name}/>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Add members"
secondary={true}
type="submit"/>
</footer>
</form>
);
break;
case STEPS.CONTACTS_SELECTION:
let contactList = _.map(ContactStore.getContacts(), (contact, i) => {
return (
<ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/>
);
});
stepForm = (
<form className="group-members" onSubmit={this.onMembersSubmit}>
<div className="count">{this.state.selectedUserIds.size} Members</div>
<div className="modal-new__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Create group"
secondary={true}
type="submit"/>
</footer>
</form>
);
break;
}
return stepForm;
}
onContactToggle = (contact, isSelected) => {
if (isSelected) {
this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)});
} else {
this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)});
}
}
onNameChange = event => {
event.preventDefault();
this.setState({name: event.target.value});
}
onNameSubmit = event => {
event.preventDefault();
if (this.state.name) {
let name = this.state.name.trim();
if (name.length > 0) {
this.setState({step: STEPS.CONTACTS_SELECTION});
}
}
}
onMembersSubmit =event => {
event.preventDefault();
CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS());
}
}
export default CreateGroupForm;
|
ajax/libs/rxjs/2.3.25/rx.lite.js | gereon/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed(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;
}
// 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;
})();
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));
/** 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 SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
var onGlobalPostMessage = function (event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
var notification = new Notification('E');
notification.exception = e;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (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 an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(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 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 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));
/**
* 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)
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
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);
};
/**
* 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);
};
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);
};
/**
* 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);
};
/**
* 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);
};
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; });
};
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 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);
};
/**
* 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 createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (!!root.Ember && typeof root.Ember.addListener === 'function') {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var 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);
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
o.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
o.onError(ex);
return;
}
o.onNext(res);
}
if (isDone && values[1]) {
o.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
o.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
o.onNext(q.shift());
}
o.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
o.onNext(q.shift());
}
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
(!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted();
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
(!this.enableQueue || this.queue.length === 0) && this.subject.onError(error);
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(value);
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
return this.queue.length !== 0 ?
{ numberOfItems: numberOfItems, returnValue: true } :
{ numberOfItems: numberOfItems, returnValue: false };
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function 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 InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(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));
/**
* 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));
/**
* 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));
|
ajax/libs/primereact/6.5.0/core/core.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { CSSTransition as CSSTransition$1 } from 'react-transition-group';
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _arrayLikeToArray$2(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _unsupportedIterableToArray$2(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$2(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen);
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest();
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function classNames() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args) {
var classes = [];
for (var i = 0; i < args.length; i++) {
var className = args[i];
if (!className) continue;
var type = _typeof(className);
if (type === 'string' || type === 'number') {
classes.push(className);
} else if (type === 'object') {
var _classes = Array.isArray(className) ? className : Object.entries(className).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
return !!value ? key : null;
});
classes = _classes.length ? classes.concat(_classes.filter(function (c) {
return !!c;
})) : classes;
}
}
return classes.join(' ');
}
return undefined;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); }
function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var DomHandler = /*#__PURE__*/function () {
function DomHandler() {
_classCallCheck(this, DomHandler);
}
_createClass(DomHandler, null, [{
key: "innerWidth",
value: function innerWidth(el) {
if (el) {
var width = el.offsetWidth;
var style = getComputedStyle(el);
width += parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
return width;
}
return 0;
}
}, {
key: "width",
value: function width(el) {
if (el) {
var width = el.offsetWidth;
var style = getComputedStyle(el);
width -= parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
return width;
}
return 0;
}
}, {
key: "getWindowScrollTop",
value: function getWindowScrollTop() {
var doc = document.documentElement;
return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
}
}, {
key: "getWindowScrollLeft",
value: function getWindowScrollLeft() {
var doc = document.documentElement;
return (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
}
}, {
key: "getOuterWidth",
value: function getOuterWidth(el, margin) {
if (el) {
var width = el.offsetWidth;
if (margin) {
var style = getComputedStyle(el);
width += parseFloat(style.marginLeft) + parseFloat(style.marginRight);
}
return width;
}
return 0;
}
}, {
key: "getOuterHeight",
value: function getOuterHeight(el, margin) {
if (el) {
var height = el.offsetHeight;
if (margin) {
var style = getComputedStyle(el);
height += parseFloat(style.marginTop) + parseFloat(style.marginBottom);
}
return height;
}
return 0;
}
}, {
key: "getClientHeight",
value: function getClientHeight(el, margin) {
if (el) {
var height = el.clientHeight;
if (margin) {
var style = getComputedStyle(el);
height += parseFloat(style.marginTop) + parseFloat(style.marginBottom);
}
return height;
}
return 0;
}
}, {
key: "getViewport",
value: function getViewport() {
var win = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
w = win.innerWidth || e.clientWidth || g.clientWidth,
h = win.innerHeight || e.clientHeight || g.clientHeight;
return {
width: w,
height: h
};
}
}, {
key: "getOffset",
value: function getOffset(el) {
if (el) {
var rect = el.getBoundingClientRect();
return {
top: rect.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0),
left: rect.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0)
};
}
return {
top: 'auto',
left: 'auto'
};
}
}, {
key: "index",
value: function index(element) {
if (element) {
var children = element.parentNode.childNodes;
var num = 0;
for (var i = 0; i < children.length; i++) {
if (children[i] === element) return num;
if (children[i].nodeType === 1) num++;
}
}
return -1;
}
}, {
key: "addMultipleClasses",
value: function addMultipleClasses(element, className) {
if (element && className) {
if (element.classList) {
var styles = className.split(' ');
for (var i = 0; i < styles.length; i++) {
element.classList.add(styles[i]);
}
} else {
var _styles = className.split(' ');
for (var _i = 0; _i < _styles.length; _i++) {
element.className += ' ' + _styles[_i];
}
}
}
}
}, {
key: "addClass",
value: function addClass(element, className) {
if (element && className) {
if (element.classList) element.classList.add(className);else element.className += ' ' + className;
}
}
}, {
key: "removeClass",
value: function removeClass(element, className) {
if (element && className) {
if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}
}, {
key: "hasClass",
value: function hasClass(element, className) {
if (element) {
if (element.classList) return element.classList.contains(className);else return new RegExp('(^| )' + className + '( |$)', 'gi').test(element.className);
}
}
}, {
key: "find",
value: function find(element, selector) {
return element ? Array.from(element.querySelectorAll(selector)) : [];
}
}, {
key: "findSingle",
value: function findSingle(element, selector) {
if (element) {
return element.querySelector(selector);
}
return null;
}
}, {
key: "getHeight",
value: function getHeight(el) {
if (el) {
var height = el.offsetHeight;
var style = getComputedStyle(el);
height -= parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
return height;
}
return 0;
}
}, {
key: "getWidth",
value: function getWidth(el) {
if (el) {
var width = el.offsetWidth;
var style = getComputedStyle(el);
width -= parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth);
return width;
}
return 0;
}
}, {
key: "alignOverlay",
value: function alignOverlay(overlay, target, appendTo) {
if (overlay && target) {
if (appendTo === 'self') {
this.relativePosition(overlay, target);
} else {
overlay.style.minWidth = DomHandler.getOuterWidth(target) + 'px';
this.absolutePosition(overlay, target);
}
}
}
}, {
key: "absolutePosition",
value: function absolutePosition(element, target) {
if (element) {
var elementDimensions = element.offsetParent ? {
width: element.offsetWidth,
height: element.offsetHeight
} : this.getHiddenElementDimensions(element);
var elementOuterHeight = elementDimensions.height;
var elementOuterWidth = elementDimensions.width;
var targetOuterHeight = target.offsetHeight;
var targetOuterWidth = target.offsetWidth;
var targetOffset = target.getBoundingClientRect();
var windowScrollTop = this.getWindowScrollTop();
var windowScrollLeft = this.getWindowScrollLeft();
var viewport = this.getViewport();
var top, left;
if (targetOffset.top + targetOuterHeight + elementOuterHeight > viewport.height) {
top = targetOffset.top + windowScrollTop - elementOuterHeight;
if (top < 0) {
top = windowScrollTop;
}
element.style.transformOrigin = 'bottom';
} else {
top = targetOuterHeight + targetOffset.top + windowScrollTop;
element.style.transformOrigin = 'top';
}
if (targetOffset.left + targetOuterWidth + elementOuterWidth > viewport.width) left = Math.max(0, targetOffset.left + windowScrollLeft + targetOuterWidth - elementOuterWidth);else left = targetOffset.left + windowScrollLeft;
element.style.top = top + 'px';
element.style.left = left + 'px';
}
}
}, {
key: "relativePosition",
value: function relativePosition(element, target) {
if (element) {
var elementDimensions = element.offsetParent ? {
width: element.offsetWidth,
height: element.offsetHeight
} : this.getHiddenElementDimensions(element);
var targetHeight = target.offsetHeight;
var targetOffset = target.getBoundingClientRect();
var viewport = this.getViewport();
var top, left;
if (targetOffset.top + targetHeight + elementDimensions.height > viewport.height) {
top = -1 * elementDimensions.height;
if (targetOffset.top + top < 0) {
top = -1 * targetOffset.top;
}
element.style.transformOrigin = 'bottom';
} else {
top = targetHeight;
element.style.transformOrigin = 'top';
}
if (elementDimensions.width > viewport.width) {
// element wider then viewport and cannot fit on screen (align at left side of viewport)
left = targetOffset.left * -1;
} else if (targetOffset.left + elementDimensions.width > viewport.width) {
// element wider then viewport but can be fit on screen (align at right side of viewport)
left = (targetOffset.left + elementDimensions.width - viewport.width) * -1;
} else {
// element fits on screen (align with target)
left = 0;
}
element.style.top = top + 'px';
element.style.left = left + 'px';
}
}
}, {
key: "flipfitCollision",
value: function flipfitCollision(element, target) {
var _this = this;
var my = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'left top';
var at = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'left bottom';
var callback = arguments.length > 4 ? arguments[4] : undefined;
var targetOffset = target.getBoundingClientRect();
var viewport = this.getViewport();
var myArr = my.split(' ');
var atArr = at.split(' ');
var getPositionValue = function getPositionValue(arr, isOffset) {
return isOffset ? +arr.substring(arr.search(/(\+|-)/g)) || 0 : arr.substring(0, arr.search(/(\+|-)/g)) || arr;
};
var position = {
my: {
x: getPositionValue(myArr[0]),
y: getPositionValue(myArr[1] || myArr[0]),
offsetX: getPositionValue(myArr[0], true),
offsetY: getPositionValue(myArr[1] || myArr[0], true)
},
at: {
x: getPositionValue(atArr[0]),
y: getPositionValue(atArr[1] || atArr[0]),
offsetX: getPositionValue(atArr[0], true),
offsetY: getPositionValue(atArr[1] || atArr[0], true)
}
};
var myOffset = {
left: function left() {
var totalOffset = position.my.offsetX + position.at.offsetX;
return totalOffset + targetOffset.left + (position.my.x === 'left' ? 0 : -1 * (position.my.x === 'center' ? _this.getOuterWidth(element) / 2 : _this.getOuterWidth(element)));
},
top: function top() {
var totalOffset = position.my.offsetY + position.at.offsetY;
return totalOffset + targetOffset.top + (position.my.y === 'top' ? 0 : -1 * (position.my.y === 'center' ? _this.getOuterHeight(element) / 2 : _this.getOuterHeight(element)));
}
};
var alignWithAt = {
count: {
x: 0,
y: 0
},
left: function left() {
var left = myOffset.left();
var scrollLeft = DomHandler.getWindowScrollLeft();
element.style.left = left + scrollLeft + 'px';
if (this.count.x === 2) {
element.style.left = scrollLeft + 'px';
this.count.x = 0;
} else if (left < 0) {
this.count.x++;
position.my.x = 'left';
position.at.x = 'right';
position.my.offsetX *= -1;
position.at.offsetX *= -1;
this.right();
}
},
right: function right() {
var left = myOffset.left() + DomHandler.getOuterWidth(target);
var scrollLeft = DomHandler.getWindowScrollLeft();
element.style.left = left + scrollLeft + 'px';
if (this.count.x === 2) {
element.style.left = viewport.width - DomHandler.getOuterWidth(element) + scrollLeft + 'px';
this.count.x = 0;
} else if (left + DomHandler.getOuterWidth(element) > viewport.width) {
this.count.x++;
position.my.x = 'right';
position.at.x = 'left';
position.my.offsetX *= -1;
position.at.offsetX *= -1;
this.left();
}
},
top: function top() {
var top = myOffset.top();
var scrollTop = DomHandler.getWindowScrollTop();
element.style.top = top + scrollTop + 'px';
if (this.count.y === 2) {
element.style.left = scrollTop + 'px';
this.count.y = 0;
} else if (top < 0) {
this.count.y++;
position.my.y = 'top';
position.at.y = 'bottom';
position.my.offsetY *= -1;
position.at.offsetY *= -1;
this.bottom();
}
},
bottom: function bottom() {
var top = myOffset.top() + DomHandler.getOuterHeight(target);
var scrollTop = DomHandler.getWindowScrollTop();
element.style.top = top + scrollTop + 'px';
if (this.count.y === 2) {
element.style.left = viewport.height - DomHandler.getOuterHeight(element) + scrollTop + 'px';
this.count.y = 0;
} else if (top + DomHandler.getOuterHeight(target) > viewport.height) {
this.count.y++;
position.my.y = 'bottom';
position.at.y = 'top';
position.my.offsetY *= -1;
position.at.offsetY *= -1;
this.top();
}
},
center: function center(axis) {
if (axis === 'y') {
var top = myOffset.top() + DomHandler.getOuterHeight(target) / 2;
element.style.top = top + DomHandler.getWindowScrollTop() + 'px';
if (top < 0) {
this.bottom();
} else if (top + DomHandler.getOuterHeight(target) > viewport.height) {
this.top();
}
} else {
var left = myOffset.left() + DomHandler.getOuterWidth(target) / 2;
element.style.left = left + DomHandler.getWindowScrollLeft() + 'px';
if (left < 0) {
this.left();
} else if (left + DomHandler.getOuterWidth(element) > viewport.width) {
this.right();
}
}
}
};
alignWithAt[position.at.x]('x');
alignWithAt[position.at.y]('y');
if (this.isFunction(callback)) {
callback(position);
}
}
}, {
key: "findCollisionPosition",
value: function findCollisionPosition(position) {
if (position) {
var isAxisY = position === 'top' || position === 'bottom';
var myXPosition = position === 'left' ? 'right' : 'left';
var myYPosition = position === 'top' ? 'bottom' : 'top';
if (isAxisY) {
return {
axis: 'y',
my: "center ".concat(myYPosition),
at: "center ".concat(position)
};
}
return {
axis: 'x',
my: "".concat(myXPosition, " center"),
at: "".concat(position, " center")
};
}
}
}, {
key: "getParents",
value: function getParents(element) {
var parents = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return element['parentNode'] === null ? parents : this.getParents(element.parentNode, parents.concat([element.parentNode]));
}
}, {
key: "getScrollableParents",
value: function getScrollableParents(element) {
var scrollableParents = [];
if (element) {
var parents = this.getParents(element);
var overflowRegex = /(auto|scroll)/;
var overflowCheck = function overflowCheck(node) {
var styleDeclaration = window['getComputedStyle'](node, null);
return overflowRegex.test(styleDeclaration.getPropertyValue('overflow')) || overflowRegex.test(styleDeclaration.getPropertyValue('overflowX')) || overflowRegex.test(styleDeclaration.getPropertyValue('overflowY'));
};
var _iterator = _createForOfIteratorHelper$1(parents),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var parent = _step.value;
var scrollSelectors = parent.nodeType === 1 && parent.dataset['scrollselectors'];
if (scrollSelectors) {
var selectors = scrollSelectors.split(',');
var _iterator2 = _createForOfIteratorHelper$1(selectors),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var selector = _step2.value;
var el = this.findSingle(parent, selector);
if (el && overflowCheck(el)) {
scrollableParents.push(el);
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
if (parent.nodeType !== 9 && overflowCheck(parent)) {
scrollableParents.push(parent);
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
return scrollableParents;
}
}, {
key: "getHiddenElementOuterHeight",
value: function getHiddenElementOuterHeight(element) {
if (element) {
element.style.visibility = 'hidden';
element.style.display = 'block';
var elementHeight = element.offsetHeight;
element.style.display = '';
element.style.visibility = '';
return elementHeight;
}
return 0;
}
}, {
key: "getHiddenElementOuterWidth",
value: function getHiddenElementOuterWidth(element) {
if (element) {
element.style.visibility = 'hidden';
element.style.display = 'block';
var elementWidth = element.offsetWidth;
element.style.display = '';
element.style.visibility = '';
return elementWidth;
}
return 0;
}
}, {
key: "getHiddenElementDimensions",
value: function getHiddenElementDimensions(element) {
var dimensions = {};
if (element) {
element.style.visibility = 'hidden';
element.style.display = 'block';
dimensions.width = element.offsetWidth;
dimensions.height = element.offsetHeight;
element.style.display = '';
element.style.visibility = '';
}
return dimensions;
}
}, {
key: "fadeIn",
value: function fadeIn(element, duration) {
if (element) {
element.style.opacity = 0;
var last = +new Date();
var opacity = 0;
var tick = function tick() {
opacity = +element.style.opacity + (new Date().getTime() - last) / duration;
element.style.opacity = opacity;
last = +new Date();
if (+opacity < 1) {
window.requestAnimationFrame && requestAnimationFrame(tick) || setTimeout(tick, 16);
}
};
tick();
}
}
}, {
key: "fadeOut",
value: function fadeOut(element, duration) {
if (element) {
var opacity = 1,
interval = 50,
gap = interval / duration;
var fading = setInterval(function () {
opacity -= gap;
if (opacity <= 0) {
opacity = 0;
clearInterval(fading);
}
element.style.opacity = opacity;
}, interval);
}
}
}, {
key: "getUserAgent",
value: function getUserAgent() {
return navigator.userAgent;
}
}, {
key: "isIOS",
value: function isIOS() {
return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window['MSStream'];
}
}, {
key: "isAndroid",
value: function isAndroid() {
return /(android)/i.test(navigator.userAgent);
}
}, {
key: "isFunction",
value: function isFunction(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
}
}, {
key: "appendChild",
value: function appendChild(element, target) {
if (this.isElement(target)) target.appendChild(element);else if (target.el && target.el.nativeElement) target.el.nativeElement.appendChild(element);else throw new Error('Cannot append ' + target + ' to ' + element);
}
}, {
key: "removeChild",
value: function removeChild(element, target) {
if (this.isElement(target)) target.removeChild(element);else if (target.el && target.el.nativeElement) target.el.nativeElement.removeChild(element);else throw new Error('Cannot remove ' + element + ' from ' + target);
}
}, {
key: "isElement",
value: function isElement(obj) {
return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? obj instanceof HTMLElement : obj && _typeof(obj) === "object" && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === "string";
}
}, {
key: "scrollInView",
value: function scrollInView(container, item) {
var borderTopValue = getComputedStyle(container).getPropertyValue('borderTopWidth');
var borderTop = borderTopValue ? parseFloat(borderTopValue) : 0;
var paddingTopValue = getComputedStyle(container).getPropertyValue('paddingTop');
var paddingTop = paddingTopValue ? parseFloat(paddingTopValue) : 0;
var containerRect = container.getBoundingClientRect();
var itemRect = item.getBoundingClientRect();
var offset = itemRect.top + document.body.scrollTop - (containerRect.top + document.body.scrollTop) - borderTop - paddingTop;
var scroll = container.scrollTop;
var elementHeight = container.clientHeight;
var itemHeight = this.getOuterHeight(item);
if (offset < 0) {
container.scrollTop = scroll + offset;
} else if (offset + itemHeight > elementHeight) {
container.scrollTop = scroll + offset - elementHeight + itemHeight;
}
}
}, {
key: "clearSelection",
value: function clearSelection() {
if (window.getSelection) {
if (window.getSelection().empty) {
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges && window.getSelection().rangeCount > 0 && window.getSelection().getRangeAt(0).getClientRects().length > 0) {
window.getSelection().removeAllRanges();
}
} else if (document['selection'] && document['selection'].empty) {
try {
document['selection'].empty();
} catch (error) {//ignore IE bug
}
}
}
}, {
key: "calculateScrollbarWidth",
value: function calculateScrollbarWidth(el) {
if (el) {
var style = getComputedStyle(el);
return el.offsetWidth - el.clientWidth - parseFloat(style.borderLeftWidth) - parseFloat(style.borderRightWidth);
} else {
if (this.calculatedScrollbarWidth != null) return this.calculatedScrollbarWidth;
var scrollDiv = document.createElement("div");
scrollDiv.className = "p-scrollbar-measure";
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
this.calculatedScrollbarWidth = scrollbarWidth;
return scrollbarWidth;
}
}
}, {
key: "getBrowser",
value: function getBrowser() {
if (!this.browser) {
var matched = this.resolveUserAgent();
this.browser = {};
if (matched.browser) {
this.browser[matched.browser] = true;
this.browser['version'] = matched.version;
}
if (this.browser['chrome']) {
this.browser['webkit'] = true;
} else if (this.browser['webkit']) {
this.browser['safari'] = true;
}
}
return this.browser;
}
}, {
key: "resolveUserAgent",
value: function resolveUserAgent() {
var ua = navigator.userAgent.toLowerCase();
var match = /(chrome)[ ]([\w.]+)/.exec(ua) || /(webkit)[ ]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ ]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || [];
return {
browser: match[1] || "",
version: match[2] || "0"
};
}
}, {
key: "isVisible",
value: function isVisible(element) {
return element && element.offsetParent != null;
}
}, {
key: "getFocusableElements",
value: function getFocusableElements(element) {
var focusableElements = DomHandler.find(element, "button:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden]),\n [href][clientHeight][clientWidth]:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden]),\n input:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden]), select:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden]),\n textarea:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden]), [tabIndex]:not([tabIndex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden]),\n [contenteditable]:not([tabIndex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])");
var visibleFocusableElements = [];
var _iterator3 = _createForOfIteratorHelper$1(focusableElements),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var focusableElement = _step3.value;
if (getComputedStyle(focusableElement).display !== "none" && getComputedStyle(focusableElement).visibility !== "hidden") visibleFocusableElements.push(focusableElement);
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
return visibleFocusableElements;
}
}, {
key: "getFirstFocusableElement",
value: function getFirstFocusableElement(element) {
var focusableElements = DomHandler.getFocusableElements(element);
return focusableElements.length > 0 ? focusableElements[0] : null;
}
}, {
key: "getLastFocusableElement",
value: function getLastFocusableElement(element) {
var focusableElements = DomHandler.getFocusableElements(element);
return focusableElements.length > 0 ? focusableElements[focusableElements.length - 1] : null;
}
}, {
key: "getCursorOffset",
value: function getCursorOffset(el, prevText, nextText, currentText) {
if (el) {
var style = getComputedStyle(el);
var ghostDiv = document.createElement('div');
ghostDiv.style.position = 'absolute';
ghostDiv.style.top = '0px';
ghostDiv.style.left = '0px';
ghostDiv.style.visibility = 'hidden';
ghostDiv.style.pointerEvents = 'none';
ghostDiv.style.overflow = style.overflow;
ghostDiv.style.width = style.width;
ghostDiv.style.height = style.height;
ghostDiv.style.padding = style.padding;
ghostDiv.style.border = style.border;
ghostDiv.style.overflowWrap = style.overflowWrap;
ghostDiv.style.whiteSpace = style.whiteSpace;
ghostDiv.style.lineHeight = style.lineHeight;
ghostDiv.innerHTML = prevText.replace(/\r\n|\r|\n/g, '<br />');
var ghostSpan = document.createElement('span');
ghostSpan.textContent = currentText;
ghostDiv.appendChild(ghostSpan);
var text = document.createTextNode(nextText);
ghostDiv.appendChild(text);
document.body.appendChild(ghostDiv);
var offsetLeft = ghostSpan.offsetLeft,
offsetTop = ghostSpan.offsetTop,
clientHeight = ghostSpan.clientHeight;
document.body.removeChild(ghostDiv);
return {
left: Math.abs(offsetLeft - el.scrollLeft),
top: Math.abs(offsetTop - el.scrollTop) + clientHeight
};
}
return {
top: 'auto',
left: 'auto'
};
}
}]);
return DomHandler;
}();
var ConnectedOverlayScrollHandler = /*#__PURE__*/function () {
function ConnectedOverlayScrollHandler(element) {
var listener = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
_classCallCheck(this, ConnectedOverlayScrollHandler);
this.element = element;
this.listener = listener;
}
_createClass(ConnectedOverlayScrollHandler, [{
key: "bindScrollListener",
value: function bindScrollListener() {
this.scrollableParents = DomHandler.getScrollableParents(this.element);
for (var i = 0; i < this.scrollableParents.length; i++) {
this.scrollableParents[i].addEventListener('scroll', this.listener);
}
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.scrollableParents) {
for (var i = 0; i < this.scrollableParents.length; i++) {
this.scrollableParents[i].removeEventListener('scroll', this.listener);
}
}
}
}, {
key: "destroy",
value: function destroy() {
this.unbindScrollListener();
this.element = null;
this.listener = null;
this.scrollableParents = null;
}
}]);
return ConnectedOverlayScrollHandler;
}();
function EventBus () {
var allHandlers = new Map();
return {
on: function on(type, handler) {
var handlers = allHandlers.get(type);
if (!handlers) handlers = [handler];else handlers.push(handler);
allHandlers.set(type, handlers);
},
off: function off(type, handler) {
var handlers = allHandlers.get(type);
handlers && handlers.splice(handlers.indexOf(handler) >>> 0, 1);
},
emit: function emit(type, evt) {
var handlers = allHandlers.get(type);
handlers && handlers.slice().forEach(function (handler) {
return handler(evt);
});
}
};
}
var ObjectUtils = /*#__PURE__*/function () {
function ObjectUtils() {
_classCallCheck(this, ObjectUtils);
}
_createClass(ObjectUtils, null, [{
key: "equals",
value: function equals(obj1, obj2, field) {
if (field && obj1 && _typeof(obj1) === 'object' && obj2 && _typeof(obj2) === 'object') return this.resolveFieldData(obj1, field) === this.resolveFieldData(obj2, field);else return this.deepEquals(obj1, obj2);
}
}, {
key: "deepEquals",
value: function deepEquals(a, b) {
if (a === b) return true;
if (a && b && _typeof(a) == 'object' && _typeof(b) == 'object') {
var arrA = Array.isArray(a),
arrB = Array.isArray(b),
i,
length,
key;
if (arrA && arrB) {
length = a.length;
if (length !== b.length) return false;
for (i = length; i-- !== 0;) {
if (!this.deepEquals(a[i], b[i])) return false;
}
return true;
}
if (arrA !== arrB) return false;
var dateA = a instanceof Date,
dateB = b instanceof Date;
if (dateA !== dateB) return false;
if (dateA && dateB) return a.getTime() === b.getTime();
var regexpA = a instanceof RegExp,
regexpB = b instanceof RegExp;
if (regexpA !== regexpB) return false;
if (regexpA && regexpB) return a.toString() === b.toString();
var keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;) {
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
}
for (i = length; i-- !== 0;) {
key = keys[i];
if (!this.deepEquals(a[key], b[key])) return false;
}
return true;
}
/*eslint no-self-compare: "off"*/
return a !== a && b !== b;
}
}, {
key: "resolveFieldData",
value: function resolveFieldData(data, field) {
if (data && Object.keys(data).length && field) {
if (this.isFunction(field)) {
return field(data);
} else if (field.indexOf('.') === -1) {
return data[field];
} else {
var fields = field.split('.');
var value = data;
for (var i = 0, len = fields.length; i < len; ++i) {
if (value == null) {
return null;
}
value = value[fields[i]];
}
return value;
}
} else {
return null;
}
}
}, {
key: "isFunction",
value: function isFunction(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
}
}, {
key: "findDiffKeys",
value: function findDiffKeys(obj1, obj2) {
if (!obj1 || !obj2) {
return {};
}
return Object.keys(obj1).filter(function (key) {
return !obj2.hasOwnProperty(key);
}).reduce(function (result, current) {
result[current] = obj1[current];
return result;
}, {});
}
}, {
key: "reorderArray",
value: function reorderArray(value, from, to) {
var target;
if (value && from !== to) {
if (to >= value.length) {
target = to - value.length;
while (target-- + 1) {
value.push(undefined);
}
}
value.splice(to, 0, value.splice(from, 1)[0]);
}
}
}, {
key: "findIndexInList",
value: function findIndexInList(value, list, dataKey) {
var _this = this;
if (list) {
return dataKey ? list.findIndex(function (item) {
return _this.equals(item, value, dataKey);
}) : list.findIndex(function (item) {
return item === value;
});
}
return -1;
}
}, {
key: "getJSXElement",
value: function getJSXElement(obj) {
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
return this.isFunction(obj) ? obj.apply(void 0, params) : obj;
}
}, {
key: "removeAccents",
value: function removeAccents(str) {
if (str && str.search(/[\xC0-\xFF]/g) > -1) {
str = str.replace(/[\xC0-\xC5]/g, "A").replace(/[\xC6]/g, "AE").replace(/[\xC7]/g, "C").replace(/[\xC8-\xCB]/g, "E").replace(/[\xCC-\xCF]/g, "I").replace(/[\xD0]/g, "D").replace(/[\xD1]/g, "N").replace(/[\xD2-\xD6\xD8]/g, "O").replace(/[\xD9-\xDC]/g, "U").replace(/[\xDD]/g, "Y").replace(/[\xDE]/g, "P").replace(/[\xE0-\xE5]/g, "a").replace(/[\xE6]/g, "ae").replace(/[\xE7]/g, "c").replace(/[\xE8-\xEB]/g, "e").replace(/[\xEC-\xEF]/g, "i").replace(/[\xF1]/g, "n").replace(/[\xF2-\xF6\xF8]/g, "o").replace(/[\xF9-\xFC]/g, "u").replace(/[\xFE]/g, "p").replace(/[\xFD\xFF]/g, "y");
}
return str;
}
}, {
key: "isEmpty",
value: function isEmpty(value) {
return value === null || value === undefined || value === '' || Array.isArray(value) && value.length === 0 || _typeof(value) === 'object' && Object.keys(value).length === 0;
}
}, {
key: "isNotEmpty",
value: function isNotEmpty(value) {
return !this.isEmpty(value);
}
}]);
return ObjectUtils;
}();
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var FilterUtils = /*#__PURE__*/function () {
function FilterUtils() {
_classCallCheck(this, FilterUtils);
}
_createClass(FilterUtils, null, [{
key: "filter",
value: function filter(value, fields, filterValue, filterMatchMode, filterLocale) {
var filteredItems = [];
var filterText = ObjectUtils.removeAccents(filterValue).toLocaleLowerCase(filterLocale);
if (value) {
var _iterator = _createForOfIteratorHelper(value),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var item = _step.value;
var _iterator2 = _createForOfIteratorHelper(fields),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var field = _step2.value;
var fieldValue = ObjectUtils.removeAccents(String(ObjectUtils.resolveFieldData(item, field))).toLocaleLowerCase(filterLocale);
if (FilterUtils[filterMatchMode](fieldValue, filterText, filterLocale)) {
filteredItems.push(item);
break;
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
return filteredItems;
}
}, {
key: "startsWith",
value: function startsWith(value, filter, filterLocale) {
if (filter === undefined || filter === null || filter.trim() === '') {
return true;
}
if (value === undefined || value === null) {
return false;
}
var filterValue = ObjectUtils.removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);
var stringValue = ObjectUtils.removeAccents(value.toString()).toLocaleLowerCase(filterLocale);
return stringValue.slice(0, filterValue.length) === filterValue;
}
}, {
key: "contains",
value: function contains(value, filter, filterLocale) {
if (filter === undefined || filter === null || typeof filter === 'string' && filter.trim() === '') {
return true;
}
if (value === undefined || value === null) {
return false;
}
var filterValue = ObjectUtils.removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);
var stringValue = ObjectUtils.removeAccents(value.toString()).toLocaleLowerCase(filterLocale);
return stringValue.indexOf(filterValue) !== -1;
}
}, {
key: "endsWith",
value: function endsWith(value, filter, filterLocale) {
if (filter === undefined || filter === null || filter.trim() === '') {
return true;
}
if (value === undefined || value === null) {
return false;
}
var filterValue = ObjectUtils.removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);
var stringValue = ObjectUtils.removeAccents(value.toString()).toLocaleLowerCase(filterLocale);
return stringValue.indexOf(filterValue, stringValue.length - filterValue.length) !== -1;
}
}, {
key: "equals",
value: function equals(value, filter, filterLocale) {
if (filter === undefined || filter === null || typeof filter === 'string' && filter.trim() === '') {
return true;
}
if (value === undefined || value === null) {
return false;
}
if (value.getTime && filter.getTime) return value.getTime() === filter.getTime();else return ObjectUtils.removeAccents(value.toString()).toLocaleLowerCase(filterLocale) === ObjectUtils.removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);
}
}, {
key: "notEquals",
value: function notEquals(value, filter, filterLocale) {
if (filter === undefined || filter === null || typeof filter === 'string' && filter.trim() === '') {
return false;
}
if (value === undefined || value === null) {
return true;
}
if (value.getTime && filter.getTime) return value.getTime() !== filter.getTime();else return ObjectUtils.removeAccents(value.toString()).toLocaleLowerCase(filterLocale) !== ObjectUtils.removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);
}
}, {
key: "in",
value: function _in(value, filter, filterLocale) {
if (filter === undefined || filter === null || filter.length === 0) {
return true;
}
if (value === undefined || value === null) {
return false;
}
for (var i = 0; i < filter.length; i++) {
if (ObjectUtils.equals(value, filter[i])) {
return true;
}
}
return false;
}
}, {
key: "lt",
value: function lt(value, filter, filterLocale) {
if (filter === undefined || filter === null || filter.trim && filter.trim().length === 0) {
return true;
}
if (value === undefined || value === null) {
return false;
}
if (value.getTime && filter.getTime) return value.getTime() < filter.getTime();else return value < parseFloat(filter);
}
}, {
key: "lte",
value: function lte(value, filter, filterLocale) {
if (filter === undefined || filter === null || filter.trim && filter.trim().length === 0) {
return true;
}
if (value === undefined || value === null) {
return false;
}
if (value.getTime && filter.getTime) return value.getTime() <= filter.getTime();else return value <= parseFloat(filter);
}
}, {
key: "gt",
value: function gt(value, filter, filterLocale) {
if (filter === undefined || filter === null || filter.trim && filter.trim().length === 0) {
return true;
}
if (value === undefined || value === null) {
return false;
}
if (value.getTime && filter.getTime) return value.getTime() > filter.getTime();else return value > parseFloat(filter);
}
}, {
key: "gte",
value: function gte(value, filter, filterLocale) {
if (filter === undefined || filter === null || filter.trim && filter.trim().length === 0) {
return true;
}
if (value === undefined || value === null) {
return false;
}
if (value.getTime && filter.getTime) return value.getTime() >= filter.getTime();else return value >= parseFloat(filter);
}
}]);
return FilterUtils;
}();
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function mask(el, options) {
var defaultOptions = {
mask: null,
slotChar: '_',
autoClear: true,
unmask: false,
readOnly: false,
onComplete: null,
onChange: null,
onFocus: null,
onBlur: null
};
options = _objectSpread$2(_objectSpread$2({}, defaultOptions), options);
var tests, partialPosition, len, firstNonMaskPos, defs, androidChrome, lastRequiredNonMaskPos, oldVal, focusText, caretTimeoutId, buffer, defaultBuffer;
var caret = function caret(first, last) {
var range, begin, end;
if (!el.offsetParent || el !== document.activeElement) {
return;
}
if (typeof first === 'number') {
begin = first;
end = typeof last === 'number' ? last : begin;
if (el.setSelectionRange) {
el.setSelectionRange(begin, end);
} else if (el['createTextRange']) {
range = el['createTextRange']();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
} else {
if (el.setSelectionRange) {
begin = el.selectionStart;
end = el.selectionEnd;
} else if (document['selection'] && document['selection'].createRange) {
range = document['selection'].createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
return {
begin: begin,
end: end
};
}
};
var isCompleted = function isCompleted() {
for (var i = firstNonMaskPos; i <= lastRequiredNonMaskPos; i++) {
if (tests[i] && buffer[i] === getPlaceholder(i)) {
return false;
}
}
return true;
};
var getPlaceholder = function getPlaceholder(i) {
if (i < options.slotChar.length) {
return options.slotChar.charAt(i);
}
return options.slotChar.charAt(0);
};
var getValue = function getValue() {
return options.unmask ? getUnmaskedValue() : el && el.value;
};
var seekNext = function seekNext(pos) {
while (++pos < len && !tests[pos]) {
}
return pos;
};
var seekPrev = function seekPrev(pos) {
while (--pos >= 0 && !tests[pos]) {
}
return pos;
};
var shiftL = function shiftL(begin, end) {
var i, j;
if (begin < 0) {
return;
}
for (i = begin, j = seekNext(end); i < len; i++) {
if (tests[i]) {
if (j < len && tests[i].test(buffer[j])) {
buffer[i] = buffer[j];
buffer[j] = getPlaceholder(j);
} else {
break;
}
j = seekNext(j);
}
}
writeBuffer();
caret(Math.max(firstNonMaskPos, begin));
};
var shiftR = function shiftR(pos) {
var i, c, j, t;
for (i = pos, c = getPlaceholder(pos); i < len; i++) {
if (tests[i]) {
j = seekNext(i);
t = buffer[i];
buffer[i] = c;
if (j < len && tests[j].test(t)) {
c = t;
} else {
break;
}
}
}
};
var handleAndroidInput = function handleAndroidInput(e) {
var curVal = el.value;
var pos = caret();
if (oldVal && oldVal.length && oldVal.length > curVal.length) {
// a deletion or backspace happened
checkVal(true);
while (pos.begin > 0 && !tests[pos.begin - 1]) {
pos.begin--;
}
if (pos.begin === 0) {
while (pos.begin < firstNonMaskPos && !tests[pos.begin]) {
pos.begin++;
}
}
caret(pos.begin, pos.begin);
} else {
checkVal(true);
while (pos.begin < len && !tests[pos.begin]) {
pos.begin++;
}
caret(pos.begin, pos.begin);
}
if (options.onComplete && isCompleted()) {
options.onComplete({
originalEvent: e,
value: getValue()
});
}
};
var onBlur = function onBlur(e) {
checkVal();
updateModel(e);
if (options.onBlur) {
options.onBlur(e);
}
if (el.value !== focusText) {
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);
}
};
var onKeyDown = function onKeyDown(e) {
if (options.readOnly) {
return;
}
var k = e.which || e.keyCode,
pos,
begin,
end;
var iPhone = /iphone/i.test(DomHandler.getUserAgent());
oldVal = el.value; //backspace, delete, and escape get special treatment
if (k === 8 || k === 46 || iPhone && k === 127) {
pos = caret();
begin = pos.begin;
end = pos.end;
if (end - begin === 0) {
begin = k !== 46 ? seekPrev(begin) : end = seekNext(begin - 1);
end = k === 46 ? seekNext(end) : end;
}
clearBuffer(begin, end);
shiftL(begin, end - 1);
updateModel(e);
e.preventDefault();
} else if (k === 13) {
// enter
onBlur(e);
updateModel(e);
} else if (k === 27) {
// escape
el.value = focusText;
caret(0, checkVal());
updateModel(e);
e.preventDefault();
}
};
var onKeyPress = function onKeyPress(e) {
if (options.readOnly) {
return;
}
var k = e.which || e.keyCode,
pos = caret(),
p,
c,
next,
completed;
if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {
//Ignore
return;
} else if (k && k !== 13) {
if (pos.end - pos.begin !== 0) {
clearBuffer(pos.begin, pos.end);
shiftL(pos.begin, pos.end - 1);
}
p = seekNext(pos.begin - 1);
if (p < len) {
c = String.fromCharCode(k);
if (tests[p].test(c)) {
shiftR(p);
buffer[p] = c;
writeBuffer();
next = seekNext(p);
if (/android/i.test(DomHandler.getUserAgent())) {
//Path for CSP Violation on FireFox OS 1.1
var proxy = function proxy() {
caret(next);
};
setTimeout(proxy, 0);
} else {
caret(next);
}
if (pos.begin <= lastRequiredNonMaskPos) {
completed = isCompleted();
}
}
}
e.preventDefault();
}
updateModel(e);
if (options.onComplete && completed) {
options.onComplete({
originalEvent: e,
value: getValue()
});
}
};
var clearBuffer = function clearBuffer(start, end) {
var i;
for (i = start; i < end && i < len; i++) {
if (tests[i]) {
buffer[i] = getPlaceholder(i);
}
}
};
var writeBuffer = function writeBuffer() {
el.value = buffer.join('');
};
var checkVal = function checkVal(allow) {
//try to place characters where they belong
var test = el.value,
lastMatch = -1,
i,
c,
pos;
for (i = 0, pos = 0; i < len; i++) {
if (tests[i]) {
buffer[i] = getPlaceholder(i);
while (pos++ < test.length) {
c = test.charAt(pos - 1);
if (tests[i].test(c)) {
buffer[i] = c;
lastMatch = i;
break;
}
}
if (pos > test.length) {
clearBuffer(i + 1, len);
break;
}
} else {
if (buffer[i] === test.charAt(pos)) {
pos++;
}
if (i < partialPosition) {
lastMatch = i;
}
}
}
if (allow) {
writeBuffer();
} else if (lastMatch + 1 < partialPosition) {
if (options.autoClear || buffer.join('') === defaultBuffer) {
// Invalid value. Remove it and replace it with the
// mask, which is the default behavior.
if (el.value) el.value = '';
clearBuffer(0, len);
} else {
// Invalid value, but we opt to show the value to the
// user and allow them to correct their mistake.
writeBuffer();
}
} else {
writeBuffer();
el.value = el.value.substring(0, lastMatch + 1);
}
return partialPosition ? i : firstNonMaskPos;
};
var onFocus = function onFocus(e) {
if (options.readOnly) {
return;
}
clearTimeout(caretTimeoutId);
var pos;
focusText = el.value;
pos = checkVal();
caretTimeoutId = setTimeout(function () {
if (el !== document.activeElement) {
return;
}
writeBuffer();
if (pos === options.mask.replace("?", "").length) {
caret(0, pos);
} else {
caret(pos);
}
}, 10);
if (options.onFocus) {
options.onFocus(e);
}
};
var onInput = function onInput(event) {
if (androidChrome) handleAndroidInput(event);else handleInputChange(event);
};
var handleInputChange = function handleInputChange(e) {
if (options.readOnly) {
return;
}
var pos = checkVal(true);
caret(pos);
updateModel(e);
if (options.onComplete && isCompleted()) {
options.onComplete({
originalEvent: e,
value: getValue()
});
}
};
var getUnmaskedValue = function getUnmaskedValue() {
var unmaskedBuffer = [];
for (var i = 0; i < buffer.length; i++) {
var c = buffer[i];
if (tests[i] && c !== getPlaceholder(i)) {
unmaskedBuffer.push(c);
}
}
return unmaskedBuffer.join('');
};
var updateModel = function updateModel(e) {
if (options.onChange) {
var val = getValue().replace(options.slotChar, '');
options.onChange({
originalEvent: e,
value: defaultBuffer !== val ? val : ''
});
}
};
var bindEvents = function bindEvents() {
el.addEventListener('focus', onFocus);
el.addEventListener('blur', onBlur);
el.addEventListener('keydown', onKeyDown);
el.addEventListener('keypress', onKeyPress);
el.addEventListener('input', onInput);
el.addEventListener('paste', handleInputChange);
};
var unbindEvents = function unbindEvents() {
el.removeEventListener('focus', onFocus);
el.removeEventListener('blur', onBlur);
el.removeEventListener('keydown', onKeyDown);
el.removeEventListener('keypress', onKeyPress);
el.removeEventListener('input', onInput);
el.removeEventListener('paste', handleInputChange);
};
var init = function init() {
tests = [];
partialPosition = options.mask.length;
len = options.mask.length;
firstNonMaskPos = null;
defs = {
'9': '[0-9]',
'a': '[A-Za-z]',
'*': '[A-Za-z0-9]'
};
var ua = DomHandler.getUserAgent();
androidChrome = /chrome/i.test(ua) && /android/i.test(ua);
var maskTokens = options.mask.split('');
for (var i = 0; i < maskTokens.length; i++) {
var c = maskTokens[i];
if (c === '?') {
len--;
partialPosition = i;
} else if (defs[c]) {
tests.push(new RegExp(defs[c]));
if (firstNonMaskPos === null) {
firstNonMaskPos = tests.length - 1;
}
if (i < partialPosition) {
lastRequiredNonMaskPos = tests.length - 1;
}
} else {
tests.push(null);
}
}
buffer = [];
for (var _i = 0; _i < maskTokens.length; _i++) {
var _c = maskTokens[_i];
if (_c !== '?') {
if (defs[_c]) buffer.push(getPlaceholder(_i));else buffer.push(_c);
}
}
defaultBuffer = buffer.join('');
};
if (el && options.mask) {
init();
bindEvents();
}
return {
init: init,
bindEvents: bindEvents,
unbindEvents: unbindEvents,
updateModel: updateModel,
getValue: getValue
};
}
var lastId = 0;
function UniqueComponentId () {
var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'pr_id_';
lastId++;
return "".concat(prefix).concat(lastId);
}
var PrimeReact = function PrimeReact() {
_classCallCheck(this, PrimeReact);
};
_defineProperty(PrimeReact, "ripple", false);
_defineProperty(PrimeReact, "locale", 'en');
_defineProperty(PrimeReact, "autoZIndex", true);
_defineProperty(PrimeReact, "zIndex", {
modal: 1100,
overlay: 1000,
menu: 1000,
tooltip: 1100,
toast: 1200
});
_defineProperty(PrimeReact, "appendTo", null);
Object.freeze({
ALIGN_CENTER: 'pi pi-align-center',
ALIGN_JUSTIFY: 'pi pi-align-justify',
ALIGN_LEFT: 'pi pi-align-left',
ALIGN_RIGHT: 'pi pi-align-right',
AMAZON: 'pi pi-amazon',
ANDROID: 'pi pi-android',
ANGLE_DOUBLE_DOWN: 'pi pi-angle-double-down',
ANGLE_DOUBLE_LEFT: 'pi pi-angle-double-left',
ANGLE_DOUBLE_RIGHT: 'pi pi-angle-double-right',
ANGLE_DOUBLE_UP: 'pi pi-angle-double-up',
ANGLE_DOWN: 'pi pi-angle-down',
ANGLE_LEFT: 'pi pi-angle-left',
ANGLE_RIGHT: 'pi pi-angle-right',
ANGLE_UP: 'pi pi-angle-up',
APPLE: 'pi pi-apple',
ARROW_CIRCLE_DOWN: 'pi pi-arrow-circle-down',
ARROW_CIRCLE_LEFT: 'pi pi-arrow-circle-left',
ARROW_CIRCLE_RIGHT: 'pi pi-arrow-circle-right',
ARROW_CIRCLE_UP: 'pi pi-arrow-circle-up',
ARROW_DOWN: 'pi pi-arrow-down',
ARROW_LEFT: 'pi pi-arrow-left',
ARROW_RIGHT: 'pi pi-arrow-right',
ARROW_UP: 'pi pi-arrow-up',
BACKWARD: 'pi pi-backward',
BAN: 'pi pi-ban',
BARS: 'pi pi-bars',
BELL: 'pi pi-bell',
BOOK: 'pi pi-book',
BOOKMARK: 'pi pi-bookmark',
BRIEFCASE: 'pi pi-briefcase',
CALENDAR_MINUS: 'pi pi-calendar-minus',
CALENDAR_PLUS: 'pi pi-calendar-plus',
CALENDAR_TIMES: 'pi pi-calendar-times',
CALENDAR: 'pi pi-calendar',
CAMERA: 'pi pi-camera',
CARET_DOWN: 'pi pi-caret-down',
CARET_LEFT: 'pi pi-caret-left',
CARET_RIGHT: 'pi pi-caret-right',
CARET_UP: 'pi pi-caret-up',
CHART_BAR: 'pi pi-chart-bar',
CHART_LINE: 'pi pi-chart-line',
CHECK_CIRCLE: 'pi pi-check-circle',
CHECK_SQUARE: 'pi pi-check-square',
CHECK: 'pi pi-check',
CHEVRON_CIRCLE_DOWN: 'pi pi-chevron-circle-down',
CHEVRON_CIRCLE_LEFT: 'pi pi-chevron-circle-left',
CHEVRON_CIRCLE_RIGHT: 'pi pi-chevron-circle-right',
CHEVRON_CIRCLE_UP: 'pi pi-chevron-circle-up',
CHEVRON_DOWN: 'pi pi-chevron-down',
CHEVRON_LEFT: 'pi pi-chevron-left',
CHEVRON_RIGHT: 'pi pi-chevron-right',
CHEVRON_UP: 'pi pi-chevron-up',
CLOCK: 'pi pi-clock',
CLONE: 'pi pi-clone',
CLOUD_DOWNLOAD: 'pi pi-cloud-download',
CLOUD_UPLOAD: 'pi pi-cloud-upload',
CLOUD: 'pi pi-cloud',
COG: 'pi pi-cog',
COMMENT: 'pi pi-comment',
COMMENTS: 'pi pi-comments',
COMPASS: 'pi pi-compass',
COPY: 'pi pi-copy',
CREDIT_CARD: 'pi pi-credit-card',
DESKTOP: 'pi pi-desktop',
DISCORD: 'pi pi-discord',
DIRECTIONS_ALT: 'pi pi-directions-alt',
DIRECTIONS: 'pi pi-directions',
DOLLAR: 'pi pi-dollar',
DOWNLOAD: 'pi pi-download',
EJECT: 'pi pi-eject',
ELLIPSIS_H: 'pi pi-ellipsis-h',
ELLIPSIS_V: 'pi pi-ellipsis-v',
ENVELOPE: 'pi pi-envelope',
EXCLAMATION_CIRCLE: 'pi pi-exclamation-circle',
EXCLAMATION_TRIANGLE: 'pi pi-exclamation-triangle ',
EXTERNAL_LINK: 'pi pi-external-link',
EYE_SLASH: 'pi pi-eye-slash',
EYE: 'pi pi-eye',
FACEBOOK: 'pi pi-facebook',
FAST_BACKWARD: 'pi pi-fast-backward',
FAST_FORWARD: 'pi pi-fast-forward',
FILE_EXCEL: 'pi pi-file-excel',
FILE_O: 'pi pi-file-o',
FILE_PDF: 'pi pi-file-pdf',
FILE: 'pi pi-file',
FILTER: 'pi pi-filter',
FILTER_SLASH: 'pi pi-filter-slash',
FLAG: 'pi pi-flag',
FOLDER_OPEN: 'pi pi-folder-open',
FOLDER: 'pi pi-folder',
FORWARD: 'pi pi-forward',
GITHUB: 'pi pi-github',
GLOBE: 'pi pi-globe',
GOOGLE: 'pi pi-google',
HEART: 'pi pi-heart',
HOME: 'pi pi-home',
ID_CARD: 'pi pi-id-card',
IMAGE: 'pi pi-image',
IMAGES: 'pi pi-images',
INBOX: 'pi pi-inbox',
INFO_CIRCLE: 'pi pi-info-circle',
INFO: 'pi pi-info',
KEY: 'pi pi-key',
LINK: 'pi pi-link',
LIST: 'pi pi-list',
LOCK_OPEN: 'pi pi-lock-open',
LOCK: 'pi pi-lock',
MAP: 'pi pi-map',
MAP_MARKER: 'pi pi-map-marker',
MICROSOFT: 'pi pi-microsoft',
MINUS_CIRCLE: 'pi pi-minus-circle',
MINUS: 'pi pi-minus',
MOBILE: 'pi pi-mobile',
MONEY_BILL: 'pi pi-money-bill',
MOON: 'pi pi-moon',
PALETTE: 'pi pi-palette',
PAPERCLIP: 'pi pi-paperclip',
PAUSE: 'pi pi-pause',
PAYPAL: 'pi pi-paypal',
PENCIL: 'pi pi-pencil',
PERCENTAGE: 'pi pi-percentage',
PHONE: 'pi pi-phone',
PLAY: 'pi pi-play',
PLUS_CIRCLE: 'pi pi-plus-circle',
PLUS: 'pi pi-plus',
POWER_OFF: 'pi pi-power-off',
PRINT: 'pi pi-print',
QUESTION_CIRCLE: 'pi pi-question-circle',
QUESTION: 'pi pi-question',
RADIO_OFF: 'pi pi-radio-off',
RADIO_ON: 'pi pi-radio-on',
REFRESH: 'pi pi-refresh',
REPLAY: 'pi pi-replay',
REPLY: 'pi pi-reply',
SAVE: 'pi pi-save',
SEARCH_MINUS: 'pi pi-search-minus',
SEARCH_PLUS: 'pi pi-search-plus',
SEARCH: 'pi pi-search',
SEND: 'pi pi-send',
SHARE_ALT: 'pi pi-share-alt',
SHIELD: 'pi pi-shield',
SHOPPING_CART: 'pi pi-shopping-cart',
SIGN_IN: 'pi pi-sign-in',
SIGN_OUT: 'pi pi-sign-out',
SITEMAP: 'pi pi-sitemap',
SLACK: 'pi pi-slack',
SLIDERS_H: 'pi pi-sliders-h',
SLIDERS_V: 'pi pi-sliders-v',
SORT_ALPHA_ALT_DOWN: 'pi pi-sort-alpha-alt-down',
SORT_ALPHA_ALT_UP: 'pi pi-sort-alpha-alt-up',
SORT_ALPHA_DOWN: 'pi pi-sort-alpha-down',
SORT_ALPHA_UP: 'pi pi-sort-alpha-up',
SORT_ALT: 'pi pi-sort-alt',
SORT_AMOUNT_DOWN_ALT: 'pi pi-sort-amount-down-alt',
SORT_AMOUNT_DOWN: 'pi pi-sort-amount-down',
SORT_AMOUNT_UP_ALT: 'pi pi-sort-amount-up-alt',
SORT_AMOUNT_UP: 'pi pi-sort-amount-up',
SORT_DOWN: 'pi pi-sort-down',
SORT_NUMERIC_ALT_DOWN: 'pi pi-sort-numeric-alt-down',
SORT_NUMERIC_ALT_UP: 'pi pi-sort-numeric-alt-up',
SORT_NUMERIC_DOWN: 'pi pi-sort-numeric-down',
SORT_NUMERIC_UP: 'pi pi-sort-numeric-up',
SORT_UP: 'pi pi-sort-up',
SORT: 'pi pi-sort',
SPINNER: 'pi pi-spinner',
STAR_O: 'pi pi-star-o',
STAR: 'pi pi-star',
STEP_BACKWARD_ALT: 'pi pi-step-backward-alt',
STEP_BACKWARD: 'pi pi-step-backward',
STEP_FORWARD_ALT: 'pi pi-step-forward-alt',
STEP_FORWARD: 'pi pi-step-forward',
SUN: 'pi pi-sun',
TABLE: 'pi pi-table',
TABLET: 'pi pi-tablet',
TAG: 'pi pi-tag',
TAGS: 'pi pi-tags',
TH_LARGE: 'pi pi-th-large',
THUMBS_DOWN: 'pi pi-thumbs-down',
THUMBS_UP: 'pi pi-thumbs-up',
TICKET: 'pi pi-ticket',
TIMES_CIRCLE: 'pi pi-times-circle',
TIMES: 'pi pi-times',
TRASH: 'pi pi-trash',
TWITTER: 'pi pi-twitter',
UNDO: 'pi pi-undo',
UNLOCK: 'pi pi-unlock',
UPLOAD: 'pi pi-upload',
USER_EDIT: 'pi pi-user-edit',
USER_MINUS: 'pi pi-user-minus',
USER_PLUS: 'pi pi-user-plus',
USER: 'pi pi-user',
USERS: 'pi pi-users',
VIDEO: 'pi pi-video',
VIMEO: 'pi pi-vimeo',
VOLUME_DOWN: 'pi pi-volume-down',
VOLUME_OFF: 'pi pi-volume-off',
VOLUME_UP: 'pi pi-volume-up',
YOUTUBE: 'pi pi-youtube',
WALLET: 'pi pi-wallet',
WIFI: 'pi pi-wifi',
WINDOW_MAXIMIZE: 'pi pi-window-maximize',
WINDOW_MINIMIZE: 'pi pi-window-minimize'
});
Object.freeze({
SUCCESS: 'success',
INFO: 'info',
WARN: 'warn',
ERROR: 'error'
});
function handler() {
var zIndexes = [];
var generateZIndex = function generateZIndex(key, baseZIndex) {
baseZIndex = baseZIndex || getBaseZIndex(key);
var lastZIndex = getLastZIndex(key, baseZIndex);
var newZIndex = lastZIndex.value + (lastZIndex.key === key ? 0 : baseZIndex) + 1;
zIndexes.push({
key: key,
value: newZIndex
});
return newZIndex;
};
var revertZIndex = function revertZIndex(zIndex) {
zIndexes = zIndexes.filter(function (obj) {
return obj.value !== zIndex;
});
};
var getBaseZIndex = function getBaseZIndex(key) {
return PrimeReact.zIndex[key] || 999;
};
var getCurrentZIndex = function getCurrentZIndex(key) {
return getLastZIndex(key).value;
};
var getLastZIndex = function getLastZIndex(key) {
var baseZIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return (zIndexes || []).reverse().find(function (obj) {
return PrimeReact.autoZIndex ? true : obj.key === key;
}) || {
key: key,
value: baseZIndex
};
};
return {
get: function get(el) {
return el ? parseInt(el.style.zIndex, 10) || 0 : 0;
},
set: function set(key, el, baseZIndex) {
if (el) {
el.style.zIndex = String(generateZIndex(key, baseZIndex));
}
},
clear: function clear(el) {
if (el) {
revertZIndex(ZIndexUtils.get(el));
el.style.zIndex = '';
}
},
getBase: function getBase(key) {
return getBaseZIndex(key);
},
getCurrent: function getCurrent(key) {
return getCurrentZIndex(key);
}
};
}
var ZIndexUtils = handler();
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Ripple = /*#__PURE__*/function (_Component) {
_inherits(Ripple, _Component);
var _super = _createSuper$3(Ripple);
function Ripple(props) {
var _this;
_classCallCheck(this, Ripple);
_this = _super.call(this, props);
_this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Ripple, [{
key: "getTarget",
value: function getTarget() {
return this.ink && this.ink.parentElement;
}
}, {
key: "bindEvents",
value: function bindEvents() {
if (this.target) {
this.target.addEventListener('mousedown', this.onMouseDown);
}
}
}, {
key: "unbindEvents",
value: function unbindEvents() {
if (this.target) {
this.target.removeEventListener('mousedown', this.onMouseDown);
}
}
}, {
key: "onMouseDown",
value: function onMouseDown(event) {
if (!this.ink || getComputedStyle(this.ink, null).display === 'none') {
return;
}
DomHandler.removeClass(this.ink, 'p-ink-active');
if (!DomHandler.getHeight(this.ink) && !DomHandler.getWidth(this.ink)) {
var d = Math.max(DomHandler.getOuterWidth(this.target), DomHandler.getOuterHeight(this.target));
this.ink.style.height = d + 'px';
this.ink.style.width = d + 'px';
}
var offset = DomHandler.getOffset(this.target);
var x = event.pageX - offset.left + document.body.scrollTop - DomHandler.getWidth(this.ink) / 2;
var y = event.pageY - offset.top + document.body.scrollLeft - DomHandler.getHeight(this.ink) / 2;
this.ink.style.top = y + 'px';
this.ink.style.left = x + 'px';
DomHandler.addClass(this.ink, 'p-ink-active');
}
}, {
key: "onAnimationEnd",
value: function onAnimationEnd(event) {
DomHandler.removeClass(event.currentTarget, 'p-ink-active');
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.ink) {
this.target = this.getTarget();
this.bindEvents();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this.ink && !this.target) {
this.target = this.getTarget();
this.bindEvents();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.ink) {
this.target = null;
this.unbindEvents();
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
return PrimeReact.ripple && /*#__PURE__*/React.createElement("span", {
ref: function ref(el) {
return _this2.ink = el;
},
className: "p-ink",
onAnimationEnd: this.onAnimationEnd
});
}
}]);
return Ripple;
}(Component);
var KeyFilter = /*#__PURE__*/function () {
function KeyFilter() {
_classCallCheck(this, KeyFilter);
}
_createClass(KeyFilter, null, [{
key: "isNavKeyPress",
value:
/* eslint-disable */
/* eslint-enable */
function isNavKeyPress(e) {
var k = e.keyCode;
k = DomHandler.getBrowser().safari ? KeyFilter.SAFARI_KEYS[k] || k : k;
return k >= 33 && k <= 40 || k === KeyFilter.KEYS.RETURN || k === KeyFilter.KEYS.TAB || k === KeyFilter.KEYS.ESC;
}
}, {
key: "isSpecialKey",
value: function isSpecialKey(e) {
var k = e.keyCode;
return k === 9 || k === 13 || k === 27 || k === 16 || k === 17 || k >= 18 && k <= 20 || DomHandler.getBrowser().opera && !e.shiftKey && (k === 8 || k >= 33 && k <= 35 || k >= 36 && k <= 39 || k >= 44 && k <= 45);
}
}, {
key: "getKey",
value: function getKey(e) {
var k = e.keyCode || e.charCode;
return DomHandler.getBrowser().safari ? KeyFilter.SAFARI_KEYS[k] || k : k;
}
}, {
key: "getCharCode",
value: function getCharCode(e) {
return e.charCode || e.keyCode || e.which;
}
}, {
key: "onKeyPress",
value: function onKeyPress(e, keyfilter, validateOnly) {
if (validateOnly) {
return;
}
var regex = KeyFilter.DEFAULT_MASKS[keyfilter] ? KeyFilter.DEFAULT_MASKS[keyfilter] : keyfilter;
var browser = DomHandler.getBrowser();
if (e.ctrlKey || e.altKey) {
return;
}
var k = this.getKey(e);
if (browser.mozilla && (this.isNavKeyPress(e) || k === KeyFilter.KEYS.BACKSPACE || k === KeyFilter.KEYS.DELETE && e.charCode === 0)) {
return;
}
var c = this.getCharCode(e);
var cc = String.fromCharCode(c);
if (browser.mozilla && (this.isSpecialKey(e) || !cc)) {
return;
}
if (!regex.test(cc)) {
e.preventDefault();
}
}
}, {
key: "validate",
value: function validate(e, keyfilter) {
var value = e.target.value,
validatePattern = true;
if (value && !keyfilter.test(value)) {
validatePattern = false;
}
return validatePattern;
}
}]);
return KeyFilter;
}();
_defineProperty(KeyFilter, "DEFAULT_MASKS", {
pint: /[\d]/,
int: /[\d\-]/,
pnum: /[\d\.]/,
money: /[\d\.\s,]/,
num: /[\d\-\.]/,
hex: /[0-9a-f]/i,
email: /[a-z0-9_\.\-@]/i,
alpha: /[a-z_]/i,
alphanum: /[a-z0-9_]/i
});
_defineProperty(KeyFilter, "KEYS", {
TAB: 9,
RETURN: 13,
ESC: 27,
BACKSPACE: 8,
DELETE: 46
});
_defineProperty(KeyFilter, "SAFARI_KEYS", {
63234: 37,
// left
63235: 39,
// right
63232: 38,
// up
63233: 40,
// down
63276: 33,
// page up
63277: 34,
// page down
63272: 46,
// delete
63273: 36,
// home
63275: 35 // end
});
function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Portal = /*#__PURE__*/function (_Component) {
_inherits(Portal, _Component);
var _super = _createSuper$2(Portal);
function Portal(props) {
var _this;
_classCallCheck(this, Portal);
_this = _super.call(this, props);
_this.state = {
mounted: props.visible
};
return _this;
}
_createClass(Portal, [{
key: "hasDOM",
value: function hasDOM() {
return !!(typeof window !== 'undefined' && window.document && window.document.createElement);
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.hasDOM() && !this.state.mounted) {
this.setState({
mounted: true
}, this.props.onMounted);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.props.onUnmounted && this.props.onUnmounted();
}
}, {
key: "render",
value: function render() {
if (this.props.element && this.state.mounted) {
var appendTo = this.props.appendTo || PrimeReact.appendTo || document.body;
return appendTo === 'self' ? this.props.element : /*#__PURE__*/ReactDOM.createPortal(this.props.element, appendTo);
}
return null;
}
}]);
return Portal;
}(Component);
_defineProperty(Portal, "defaultProps", {
element: null,
appendTo: null,
visible: false,
onMounted: null,
onUnmounted: null
});
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function tip(props) {
var appendTo = props.appendTo || document.body;
var tooltipWrapper = document.createDocumentFragment();
DomHandler.appendChild(tooltipWrapper, appendTo);
props = _objectSpread$1(_objectSpread$1({}, props), props.options);
var tooltipEl = /*#__PURE__*/React.createElement(Tooltip, props);
ReactDOM.render(tooltipEl, tooltipWrapper);
var updateTooltip = function updateTooltip(newProps) {
props = _objectSpread$1(_objectSpread$1({}, props), newProps);
ReactDOM.render( /*#__PURE__*/React.cloneElement(tooltipEl, props), tooltipWrapper);
};
return {
destroy: function destroy() {
ReactDOM.unmountComponentAtNode(tooltipWrapper);
},
updateContent: function updateContent(newContent) {
console.warn("The 'updateContent' method has been deprecated on Tooltip. Use update(newProps) method.");
updateTooltip({
content: newContent
});
},
update: function update(newProps) {
updateTooltip(newProps);
}
};
}
var Tooltip = /*#__PURE__*/function (_Component) {
_inherits(Tooltip, _Component);
var _super = _createSuper$1(Tooltip);
function Tooltip(props) {
var _this;
_classCallCheck(this, Tooltip);
_this = _super.call(this, props);
_this.state = {
visible: false,
position: _this.props.position
};
_this.show = _this.show.bind(_assertThisInitialized(_this));
_this.hide = _this.hide.bind(_assertThisInitialized(_this));
_this.onMouseEnter = _this.onMouseEnter.bind(_assertThisInitialized(_this));
_this.onMouseLeave = _this.onMouseLeave.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Tooltip, [{
key: "isTargetContentEmpty",
value: function isTargetContentEmpty(target) {
return !(this.props.content || this.getTargetOption(target, 'tooltip'));
}
}, {
key: "isContentEmpty",
value: function isContentEmpty(target) {
return !(this.props.content || this.getTargetOption(target, 'tooltip') || this.props.children);
}
}, {
key: "isMouseTrack",
value: function isMouseTrack(target) {
return this.getTargetOption(target, 'mousetrack') || this.props.mouseTrack;
}
}, {
key: "isDisabled",
value: function isDisabled(target) {
return this.getTargetOption(target, 'disabled') === 'true' || this.hasTargetOption(target, 'disabled') || this.props.disabled;
}
}, {
key: "isAutoHide",
value: function isAutoHide() {
return this.getTargetOption(this.currentTarget, 'autohide') || this.props.autoHide;
}
}, {
key: "getTargetOption",
value: function getTargetOption(target, option) {
if (this.hasTargetOption(target, "data-pr-".concat(option))) {
return target.getAttribute("data-pr-".concat(option));
}
return null;
}
}, {
key: "hasTargetOption",
value: function hasTargetOption(target, option) {
return target && target.hasAttribute(option);
}
}, {
key: "getEvents",
value: function getEvents(target) {
var showEvent = this.getTargetOption(target, 'showevent') || this.props.showEvent;
var hideEvent = this.getTargetOption(target, 'hideevent') || this.props.hideEvent;
if (this.isMouseTrack(target)) {
showEvent = 'mousemove';
hideEvent = 'mouseleave';
} else {
var event = this.getTargetOption(target, 'event') || this.props.event;
if (event === 'focus') {
showEvent = 'focus';
hideEvent = 'blur';
}
}
return {
showEvent: showEvent,
hideEvent: hideEvent
};
}
}, {
key: "getPosition",
value: function getPosition(target) {
return this.getTargetOption(target, 'position') || this.state.position;
}
}, {
key: "getMouseTrackPosition",
value: function getMouseTrackPosition(target) {
var top = this.getTargetOption(target, 'mousetracktop') || this.props.mouseTrackTop;
var left = this.getTargetOption(target, 'mousetrackleft') || this.props.mouseTrackLeft;
return {
top: top,
left: left
};
}
}, {
key: "updateText",
value: function updateText(target, callback) {
if (this.tooltipTextEl) {
var content = this.getTargetOption(target, 'tooltip') || this.props.content;
if (content) {
this.tooltipTextEl.innerHTML = ''; // remove children
this.tooltipTextEl.appendChild(document.createTextNode(content));
callback();
} else if (this.props.children) {
callback();
}
}
}
}, {
key: "show",
value: function show(e) {
var _this2 = this;
this.currentTarget = e.currentTarget;
if (this.isContentEmpty(this.currentTarget) || this.isDisabled(this.currentTarget)) {
return;
}
var updateTooltipState = function updateTooltipState() {
_this2.updateText(_this2.currentTarget, function () {
if (_this2.props.autoZIndex && !ZIndexUtils.get(_this2.containerEl)) {
ZIndexUtils.set('tooltip', _this2.containerEl, _this2.props.baseZIndex);
}
_this2.containerEl.style.left = '';
_this2.containerEl.style.top = '';
if (_this2.isMouseTrack(_this2.currentTarget) && !_this2.containerSize) {
_this2.containerSize = {
width: DomHandler.getOuterWidth(_this2.containerEl),
height: DomHandler.getOuterHeight(_this2.containerEl)
};
}
_this2.align(_this2.currentTarget, {
x: e.pageX,
y: e.pageY
});
});
};
if (this.state.visible) {
this.applyDelay('updateDelay', updateTooltipState);
} else {
this.sendCallback(this.props.onBeforeShow, {
originalEvent: e,
target: this.currentTarget
});
this.applyDelay('showDelay', function () {
_this2.setState({
visible: true,
position: _this2.getPosition(_this2.currentTarget)
}, function () {
updateTooltipState();
_this2.sendCallback(_this2.props.onShow, {
originalEvent: e,
target: _this2.currentTarget
});
});
_this2.bindDocumentResizeListener();
_this2.bindScrollListener();
DomHandler.addClass(_this2.currentTarget, _this2.getTargetOption(_this2.currentTarget, 'classname'));
});
}
}
}, {
key: "hide",
value: function hide(e) {
var _this3 = this;
this.clearTimeouts();
if (this.state.visible) {
DomHandler.removeClass(this.currentTarget, this.getTargetOption(this.currentTarget, 'classname'));
this.sendCallback(this.props.onBeforeHide, {
originalEvent: e,
target: this.currentTarget
});
this.applyDelay('hideDelay', function () {
ZIndexUtils.clear(_this3.containerEl);
DomHandler.removeClass(_this3.containerEl, 'p-tooltip-active');
if (!_this3.isAutoHide() && _this3.allowHide === false) {
return;
}
_this3.setState({
visible: false,
position: _this3.props.position
}, function () {
if (_this3.tooltipTextEl) {
ReactDOM.unmountComponentAtNode(_this3.tooltipTextEl);
}
_this3.unbindDocumentResizeListener();
_this3.unbindScrollListener();
_this3.currentTarget = null;
_this3.scrollHandler = null;
_this3.containerSize = null;
_this3.allowHide = true;
_this3.sendCallback(_this3.props.onHide, {
originalEvent: e,
target: _this3.currentTarget
});
});
});
}
}
}, {
key: "align",
value: function align(target, coordinate) {
var _this4 = this;
var left = 0,
top = 0;
if (this.isMouseTrack(target) && coordinate) {
var containerSize = {
width: DomHandler.getOuterWidth(this.containerEl),
height: DomHandler.getOuterHeight(this.containerEl)
};
left = coordinate.x;
top = coordinate.y;
var _this$getMouseTrackPo = this.getMouseTrackPosition(target),
mouseTrackTop = _this$getMouseTrackPo.top,
mouseTrackLeft = _this$getMouseTrackPo.left;
switch (this.state.position) {
case 'left':
left -= containerSize.width + mouseTrackLeft;
top -= containerSize.height / 2 - mouseTrackTop;
break;
case 'right':
left += mouseTrackLeft;
top -= containerSize.height / 2 - mouseTrackTop;
break;
case 'top':
left -= containerSize.width / 2 - mouseTrackLeft;
top -= containerSize.height + mouseTrackTop;
break;
case 'bottom':
left -= containerSize.width / 2 - mouseTrackLeft;
top += mouseTrackTop;
break;
}
if (left <= 0 || this.containerSize.width > containerSize.width) {
this.containerEl.style.left = '0px';
this.containerEl.style.right = window.innerWidth - containerSize.width - left + 'px';
} else {
this.containerEl.style.right = '';
this.containerEl.style.left = left + 'px';
}
this.containerEl.style.top = top + 'px';
DomHandler.addClass(this.containerEl, 'p-tooltip-active');
} else {
var pos = DomHandler.findCollisionPosition(this.state.position);
var my = this.getTargetOption(target, 'my') || this.props.my || pos.my;
var at = this.getTargetOption(target, 'at') || this.props.at || pos.at;
this.containerEl.style.padding = '0px';
DomHandler.flipfitCollision(this.containerEl, target, my, at, function (currentPosition) {
var _currentPosition$at = currentPosition.at,
atX = _currentPosition$at.x,
atY = _currentPosition$at.y;
var myX = currentPosition.my.x;
var position = _this4.props.at ? atX !== 'center' && atX !== myX ? atX : atY : currentPosition.at["".concat(pos.axis)];
_this4.containerEl.style.padding = '';
_this4.setState({
position: position
}, function () {
_this4.updateContainerPosition();
DomHandler.addClass(_this4.containerEl, 'p-tooltip-active');
});
});
}
}
}, {
key: "updateContainerPosition",
value: function updateContainerPosition() {
if (this.containerEl) {
var style = getComputedStyle(this.containerEl);
if (this.state.position === 'left') this.containerEl.style.left = parseFloat(style.left) - parseFloat(style.paddingLeft) * 2 + 'px';else if (this.state.position === 'top') this.containerEl.style.top = parseFloat(style.top) - parseFloat(style.paddingTop) * 2 + 'px';
}
}
}, {
key: "onMouseEnter",
value: function onMouseEnter() {
if (!this.isAutoHide()) {
this.allowHide = false;
}
}
}, {
key: "onMouseLeave",
value: function onMouseLeave(e) {
if (!this.isAutoHide()) {
this.allowHide = true;
this.hide(e);
}
}
}, {
key: "bindDocumentResizeListener",
value: function bindDocumentResizeListener() {
var _this5 = this;
this.documentResizeListener = function (e) {
if (!DomHandler.isAndroid()) {
_this5.hide(e);
}
};
window.addEventListener('resize', this.documentResizeListener);
}
}, {
key: "unbindDocumentResizeListener",
value: function unbindDocumentResizeListener() {
if (this.documentResizeListener) {
window.removeEventListener('resize', this.documentResizeListener);
this.documentResizeListener = null;
}
}
}, {
key: "bindScrollListener",
value: function bindScrollListener() {
var _this6 = this;
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.currentTarget, function (e) {
if (_this6.state.visible) {
_this6.hide(e);
}
});
}
this.scrollHandler.bindScrollListener();
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
}
}, {
key: "bindTargetEvent",
value: function bindTargetEvent(target) {
if (target) {
var _this$getEvents = this.getEvents(target),
showEvent = _this$getEvents.showEvent,
hideEvent = _this$getEvents.hideEvent;
target.addEventListener(showEvent, this.show);
target.addEventListener(hideEvent, this.hide);
}
}
}, {
key: "unbindTargetEvent",
value: function unbindTargetEvent(target) {
if (target) {
var _this$getEvents2 = this.getEvents(target),
showEvent = _this$getEvents2.showEvent,
hideEvent = _this$getEvents2.hideEvent;
target.removeEventListener(showEvent, this.show);
target.removeEventListener(hideEvent, this.hide);
}
}
}, {
key: "applyDelay",
value: function applyDelay(delayProp, callback) {
this.clearTimeouts();
var delay = this.getTargetOption(this.currentTarget, delayProp.toLowerCase()) || this.props[delayProp];
if (!!delay) {
this["".concat(delayProp, "Timeout")] = setTimeout(function () {
return callback();
}, delay);
} else {
callback();
}
}
}, {
key: "sendCallback",
value: function sendCallback(callback) {
if (callback) {
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
callback.apply(void 0, params);
}
}
}, {
key: "clearTimeouts",
value: function clearTimeouts() {
clearTimeout(this.showDelayTimeout);
clearTimeout(this.updateDelayTimeout);
clearTimeout(this.hideDelayTimeout);
}
}, {
key: "updateTargetEvents",
value: function updateTargetEvents(target) {
this.unloadTargetEvents(target);
this.loadTargetEvents(target);
}
}, {
key: "loadTargetEvents",
value: function loadTargetEvents(target) {
this.setTargetEventOperations(target || this.props.target, 'bindTargetEvent');
}
}, {
key: "unloadTargetEvents",
value: function unloadTargetEvents(target) {
this.setTargetEventOperations(target || this.props.target, 'unbindTargetEvent');
}
}, {
key: "setTargetEventOperations",
value: function setTargetEventOperations(target, operation) {
var _this7 = this;
if (target) {
if (DomHandler.isElement(target)) {
this[operation](target);
} else {
var setEvent = function setEvent(target) {
var element = DomHandler.find(document, target);
element.forEach(function (el) {
_this7[operation](el);
});
};
if (target instanceof Array) {
target.forEach(function (t) {
setEvent(t);
});
} else {
setEvent(target);
}
}
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.props.target) {
this.loadTargetEvents();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
var _this8 = this;
if (prevProps.target !== this.props.target) {
this.unloadTargetEvents(prevProps.target);
this.loadTargetEvents();
}
if (this.state.visible) {
if (prevProps.content !== this.props.content) {
this.applyDelay('updateDelay', function () {
_this8.updateText(_this8.currentTarget, function () {
_this8.align(_this8.currentTarget);
});
});
}
if (this.currentTarget && this.isDisabled(this.currentTarget)) {
this.hide();
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.clearTimeouts();
this.unbindDocumentResizeListener();
this.unloadTargetEvents();
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
ZIndexUtils.clear(this.containerEl);
}
}, {
key: "renderElement",
value: function renderElement() {
var _this9 = this;
var tooltipClassName = classNames('p-tooltip p-component', _defineProperty({}, "p-tooltip-".concat(this.state.position), true), this.props.className);
var isTargetContentEmpty = this.isTargetContentEmpty(this.currentTarget);
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
ref: function ref(el) {
return _this9.containerEl = el;
},
className: tooltipClassName,
style: this.props.style,
role: "tooltip",
"aria-hidden": this.state.visible,
onMouseEnter: this.onMouseEnter,
onMouseLeave: this.onMouseLeave
}, /*#__PURE__*/React.createElement("div", {
className: "p-tooltip-arrow"
}), /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this9.tooltipTextEl = el;
},
className: "p-tooltip-text"
}, isTargetContentEmpty && this.props.children));
}
}, {
key: "render",
value: function render() {
if (this.state.visible) {
var element = this.renderElement();
return /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo,
visible: true
});
}
return null;
}
}]);
return Tooltip;
}(Component);
_defineProperty(Tooltip, "defaultProps", {
id: null,
target: null,
content: null,
disabled: false,
className: null,
style: null,
appendTo: null,
position: 'right',
my: null,
at: null,
event: null,
showEvent: 'mouseenter',
hideEvent: 'mouseleave',
autoZIndex: true,
baseZIndex: 0,
mouseTrack: false,
mouseTrackTop: 5,
mouseTrackLeft: 5,
showDelay: 0,
updateDelay: 0,
hideDelay: 0,
autoHide: true,
onBeforeShow: null,
onBeforeHide: null,
onShow: null,
onHide: null
});
var OverlayService = EventBus();
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var CSSTransition = /*#__PURE__*/function (_Component) {
_inherits(CSSTransition, _Component);
var _super = _createSuper(CSSTransition);
function CSSTransition(props) {
var _this;
_classCallCheck(this, CSSTransition);
_this = _super.call(this, props);
_this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this));
_this.onEntering = _this.onEntering.bind(_assertThisInitialized(_this));
_this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this));
_this.onExit = _this.onExit.bind(_assertThisInitialized(_this));
_this.onExiting = _this.onExiting.bind(_assertThisInitialized(_this));
_this.onExited = _this.onExited.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(CSSTransition, [{
key: "onEnter",
value: function onEnter(node, isAppearing) {
this.props.onEnter && this.props.onEnter(node, isAppearing); // component
this.props.options && this.props.options.onEnter && this.props.options.onEnter(node, isAppearing); // user option
}
}, {
key: "onEntering",
value: function onEntering(node, isAppearing) {
this.props.onEntering && this.props.onEntering(node, isAppearing); // component
this.props.options && this.props.options.onEntering && this.props.options.onEntering(node, isAppearing); // user option
}
}, {
key: "onEntered",
value: function onEntered(node, isAppearing) {
this.props.onEntered && this.props.onEntered(node, isAppearing); // component
this.props.options && this.props.options.onEntered && this.props.options.onEntered(node, isAppearing); // user option
}
}, {
key: "onExit",
value: function onExit(node) {
this.props.onExit && this.props.onExit(node); // component
this.props.options && this.props.options.onExit && this.props.options.onExit(node); // user option
}
}, {
key: "onExiting",
value: function onExiting(node) {
this.props.onExiting && this.props.onExiting(node); // component
this.props.options && this.props.options.onExiting && this.props.options.onExiting(node); // user option
}
}, {
key: "onExited",
value: function onExited(node) {
this.props.onExited && this.props.onExited(node); // component
this.props.options && this.props.options.onExited && this.props.options.onExited(node); // user option
}
}, {
key: "render",
value: function render() {
var immutableProps = {
nodeRef: this.props.nodeRef,
in: this.props.in,
onEnter: this.onEnter,
onEntering: this.onEntering,
onEntered: this.onEntered,
onExit: this.onExit,
onExiting: this.onExiting,
onExited: this.onExited
};
var mutableProps = {
classNames: this.props.classNames,
timeout: this.props.timeout,
unmountOnExit: this.props.unmountOnExit
};
var props = _objectSpread(_objectSpread(_objectSpread({}, mutableProps), this.props.options || {}), immutableProps);
return /*#__PURE__*/React.createElement(CSSTransition$1, props, this.props.children);
}
}]);
return CSSTransition;
}(Component);
export { CSSTransition, ConnectedOverlayScrollHandler, DomHandler, EventBus, FilterUtils, KeyFilter, ObjectUtils, OverlayService, Portal, Ripple, Tooltip, UniqueComponentId, ZIndexUtils, classNames, mask, tip };
|
modules/field_ui/field_ui.js | ttrezren/pincsf | /**
* @file
* Attaches the behaviors for the Field UI module.
*/
(function($) {
Drupal.behaviors.fieldUIFieldOverview = {
attach: function (context, settings) {
$('table#field-overview', context).once('field-overview', function () {
Drupal.fieldUIFieldOverview.attachUpdateSelects(this, settings);
});
}
};
Drupal.fieldUIFieldOverview = {
/**
* Implements dependent select dropdowns on the 'Manage fields' screen.
*/
attachUpdateSelects: function(table, settings) {
var widgetTypes = settings.fieldWidgetTypes;
var fields = settings.fields;
// Store the default text of widget selects.
$('.widget-type-select', table).each(function () {
this.initialValue = this.options[0].text;
});
// 'Field type' select updates its 'Widget' select.
$('.field-type-select', table).each(function () {
this.targetSelect = $('.widget-type-select', $(this).closest('tr'));
$(this).bind('change keyup', function () {
var selectedFieldType = this.options[this.selectedIndex].value;
var options = (selectedFieldType in widgetTypes ? widgetTypes[selectedFieldType] : []);
this.targetSelect.fieldUIPopulateOptions(options);
});
// Trigger change on initial pageload to get the right widget options
// when field type comes pre-selected (on failed validation).
$(this).trigger('change', false);
});
// 'Existing field' select updates its 'Widget' select and 'Label' textfield.
$('.field-select', table).each(function () {
this.targetSelect = $('.widget-type-select', $(this).closest('tr'));
this.targetTextfield = $('.label-textfield', $(this).closest('tr'));
this.targetTextfield
.data('field_ui_edited', false)
.bind('keyup', function (e) {
$(this).data('field_ui_edited', $(this).val() != '');
});
$(this).bind('change keyup', function (e, updateText) {
var updateText = (typeof updateText == 'undefined' ? true : updateText);
var selectedField = this.options[this.selectedIndex].value;
var selectedFieldType = (selectedField in fields ? fields[selectedField].type : null);
var selectedFieldWidget = (selectedField in fields ? fields[selectedField].widget : null);
var options = (selectedFieldType && (selectedFieldType in widgetTypes) ? widgetTypes[selectedFieldType] : []);
this.targetSelect.fieldUIPopulateOptions(options, selectedFieldWidget);
// Only overwrite the "Label" input if it has not been manually
// changed, or if it is empty.
if (updateText && !this.targetTextfield.data('field_ui_edited')) {
this.targetTextfield.val(selectedField in fields ? fields[selectedField].label : '');
}
});
// Trigger change on initial pageload to get the right widget options
// and label when field type comes pre-selected (on failed validation).
$(this).trigger('change', false);
});
}
};
/**
* Populates options in a select input.
*/
jQuery.fn.fieldUIPopulateOptions = function (options, selected) {
return this.each(function () {
var disabled = false;
if (options.length == 0) {
options = [this.initialValue];
disabled = true;
}
// If possible, keep the same widget selected when changing field type.
// This is based on textual value, since the internal value might be
// different (options_buttons vs. node_reference_buttons).
var previousSelectedText = this.options[this.selectedIndex].text;
var html = '';
jQuery.each(options, function (value, text) {
// Figure out which value should be selected. The 'selected' param
// takes precedence.
var is_selected = ((typeof selected != 'undefined' && value == selected) || (typeof selected == 'undefined' && text == previousSelectedText));
html += '<option value="' + value + '"' + (is_selected ? ' selected="selected"' : '') + '>' + text + '</option>';
});
$(this).html(html).attr('disabled', disabled ? 'disabled' : false);
});
};
Drupal.behaviors.fieldUIDisplayOverview = {
attach: function (context, settings) {
$('table#field-display-overview', context).once('field-display-overview', function() {
Drupal.fieldUIOverview.attach(this, settings.fieldUIRowsData, Drupal.fieldUIDisplayOverview);
});
}
};
Drupal.fieldUIOverview = {
/**
* Attaches the fieldUIOverview behavior.
*/
attach: function (table, rowsData, rowHandlers) {
var tableDrag = Drupal.tableDrag[table.id];
// Add custom tabledrag callbacks.
tableDrag.onDrop = this.onDrop;
tableDrag.row.prototype.onSwap = this.onSwap;
// Create row handlers.
$('tr.draggable', table).each(function () {
// Extract server-side data for the row.
var row = this;
if (row.id in rowsData) {
var data = rowsData[row.id];
data.tableDrag = tableDrag;
// Create the row handler, make it accessible from the DOM row element.
var rowHandler = new rowHandlers[data.rowHandler](row, data);
$(row).data('fieldUIRowHandler', rowHandler);
}
});
},
/**
* Event handler to be attached to form inputs triggering a region change.
*/
onChange: function () {
var $trigger = $(this);
var row = $trigger.closest('tr').get(0);
var rowHandler = $(row).data('fieldUIRowHandler');
var refreshRows = {};
refreshRows[rowHandler.name] = $trigger.get(0);
// Handle region change.
var region = rowHandler.getRegion();
if (region != rowHandler.region) {
// Remove parenting.
$('select.field-parent', row).val('');
// Let the row handler deal with the region change.
$.extend(refreshRows, rowHandler.regionChange(region));
// Update the row region.
rowHandler.region = region;
}
// Ajax-update the rows.
Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows);
},
/**
* Lets row handlers react when a row is dropped into a new region.
*/
onDrop: function () {
var dragObject = this;
var row = dragObject.rowObject.element;
var rowHandler = $(row).data('fieldUIRowHandler');
if (typeof rowHandler !== 'undefined') {
var regionRow = $(row).prevAll('tr.region-message').get(0);
var region = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
if (region != rowHandler.region) {
// Let the row handler deal with the region change.
refreshRows = rowHandler.regionChange(region);
// Update the row region.
rowHandler.region = region;
// Ajax-update the rows.
Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows);
}
}
},
/**
* Refreshes placeholder rows in empty regions while a row is being dragged.
*
* Copied from block.js.
*
* @param table
* The table DOM element.
* @param rowObject
* The tableDrag rowObject for the row being dragged.
*/
onSwap: function (draggedRow) {
var rowObject = this;
$('tr.region-message', rowObject.table).each(function () {
// If the dragged row is in this region, but above the message row, swap
// it down one space.
if ($(this).prev('tr').get(0) == rowObject.group[rowObject.group.length - 1]) {
// Prevent a recursion problem when using the keyboard to move rows up.
if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) {
rowObject.swap('after', this);
}
}
// This region has become empty.
if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').length == 0) {
$(this).removeClass('region-populated').addClass('region-empty');
}
// This region has become populated.
else if ($(this).is('.region-empty')) {
$(this).removeClass('region-empty').addClass('region-populated');
}
});
},
/**
* Triggers Ajax refresh of selected rows.
*
* The 'format type' selects can trigger a series of changes in child rows.
* The #ajax behavior is therefore not attached directly to the selects, but
* triggered manually through a hidden #ajax 'Refresh' button.
*
* @param rows
* A hash object, whose keys are the names of the rows to refresh (they
* will receive the 'ajax-new-content' effect on the server side), and
* whose values are the DOM element in the row that should get an Ajax
* throbber.
*/
AJAXRefreshRows: function (rows) {
// Separate keys and values.
var rowNames = [];
var ajaxElements = [];
$.each(rows, function (rowName, ajaxElement) {
rowNames.push(rowName);
ajaxElements.push(ajaxElement);
});
if (rowNames.length) {
// Add a throbber next each of the ajaxElements.
var $throbber = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>');
$(ajaxElements)
.addClass('progress-disabled')
.after($throbber);
// Fire the Ajax update.
$('input[name=refresh_rows]').val(rowNames.join(' '));
$('input#edit-refresh').mousedown();
// Disabled elements do not appear in POST ajax data, so we mark the
// elements disabled only after firing the request.
$(ajaxElements).attr('disabled', true);
}
}
};
/**
* Row handlers for the 'Manage display' screen.
*/
Drupal.fieldUIDisplayOverview = {};
/**
* Constructor for a 'field' row handler.
*
* This handler is used for both fields and 'extra fields' rows.
*
* @param row
* The row DOM element.
* @param data
* Additional data to be populated in the constructed object.
*/
Drupal.fieldUIDisplayOverview.field = function (row, data) {
this.row = row;
this.name = data.name;
this.region = data.region;
this.tableDrag = data.tableDrag;
// Attach change listener to the 'formatter type' select.
this.$formatSelect = $('select.field-formatter-type', row);
this.$formatSelect.change(Drupal.fieldUIOverview.onChange);
return this;
};
Drupal.fieldUIDisplayOverview.field.prototype = {
/**
* Returns the region corresponding to the current form values of the row.
*/
getRegion: function () {
return (this.$formatSelect.val() == 'hidden') ? 'hidden' : 'visible';
},
/**
* Reacts to a row being changed regions.
*
* This function is called when the row is moved to a different region, as a
* result of either :
* - a drag-and-drop action (the row's form elements then probably need to be
* updated accordingly)
* - user input in one of the form elements watched by the
* Drupal.fieldUIOverview.onChange change listener.
*
* @param region
* The name of the new region for the row.
* @return
* A hash object indicating which rows should be Ajax-updated as a result
* of the change, in the format expected by
* Drupal.displayOverview.AJAXRefreshRows().
*/
regionChange: function (region) {
// When triggered by a row drag, the 'format' select needs to be adjusted
// to the new region.
var currentValue = this.$formatSelect.val();
switch (region) {
case 'visible':
if (currentValue == 'hidden') {
// Restore the formatter back to the default formatter. Pseudo-fields do
// not have default formatters, we just return to 'visible' for those.
var value = (typeof this.defaultFormatter !== 'undefined') ? this.defaultFormatter : this.$formatSelect.find('option').val();
}
break;
default:
var value = 'hidden';
break;
}
if (value != undefined) {
this.$formatSelect.val(value);
}
var refreshRows = {};
refreshRows[this.name] = this.$formatSelect.get(0);
return refreshRows;
}
};
})(jQuery);
|
src/mixins/ListMovementMixin.js | thuringia/react-widgets | 'use strict';
import React from 'react';
import filter from '../util/filter';
import { dataText } from '../util/dataHelpers';
module.exports = {
propTypes: {
textField: React.PropTypes.string
},
first() {
return this._data()[0]
},
last() {
var data = this._data()
return data[data.length - 1]
},
prev(item, word) {
var textField = this.props.textField
, data = this._data()
, idx = data.indexOf(item)
if (idx === -1) idx = data.length;
return word
? findPrevInstance(textField, data, word, idx)
: --idx < 0 ? data[0] : data[idx]
},
next(item, word) {
var textField = this.props.textField
, data = this._data()
, idx = data.indexOf(item)
return word
? findNextInstance(textField, data, word, idx)
: ++idx === data.length ? data[data.length - 1] : data[idx]
}
}
function findNextInstance(textField, data, word, startIndex){
var matches = filter.startsWith
, idx = -1
, len = data.length
, foundStart, itemText;
word = word.toLowerCase()
while (++idx < len){
foundStart = foundStart || idx > startIndex
itemText = foundStart && dataText(data[idx], textField).toLowerCase()
if( foundStart && matches(itemText, word) )
return data[idx]
}
}
function findPrevInstance(textField, data, word, startIndex){
var matches = filter.startsWith
, idx = data.length
, foundStart, itemText;
word = word.toLowerCase()
while (--idx >= 0 ){
foundStart = foundStart || idx < startIndex
itemText = foundStart && dataText(data[idx], textField).toLowerCase()
if( foundStart && matches(itemText, word) )
return data[idx]
}
}
|
CalcApp/src/components/numberEntry.js | michelmarcondes/ReactNativeStudies | import React from 'react';
import { TextInput, StyleSheet } from 'react-native';
export default props => (
<TextInput
style={styles.field}
placeholder='000'
value={props.num}
onChangeText={newValue => { props.action(props.id, newValue); }}
keyboardType='numeric'
/>
);
const styles = StyleSheet.create({
field: {
width: 140,
height: 80,
fontSize: 20,
textAlign: 'center'
}
});
|
src/components/CallingSettingsPanel/index.js | alvita/ringcentral-js-widget | import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import formatMessage from 'format-message';
import callingOptions from 'ringcentral-integration/modules/CallingSettings/callingOptions';
import 'font-awesome/css/font-awesome.css';
import styles from './styles.scss';
import i18n from './i18n';
import BackHeader from '../BackHeader';
import Panel from '../Panel';
import Switch from '../Switch';
import IconField from '../IconField';
import InputField from '../InputField';
import TextInput from '../TextInput';
import Select from '../DropdownSelect';
export default class CallingSettingsPanel extends Component {
constructor(props) {
super(props);
this.state = {
callWith: props.callWith,
ringoutPrompt: props.ringoutPrompt,
myLocation: props.myLocation,
};
}
componentWillReceiveProps(newProps) {
if (newProps.callWith !== this.props.callWith) {
this.setState({
callWith: newProps.callWith,
});
}
if (newProps.ringoutPrompt !== this.props.ringoutPrompt) {
this.setState({
ringoutPrompt: newProps.ringoutPrompt,
});
}
if (newProps.myLocation !== this.props.myLocation) {
this.setState({
myLocation: newProps.myLocation,
});
}
}
onSave = () => {
if (typeof this.props.onSave === 'function') {
const {
callWith,
myLocation,
ringoutPrompt,
} = this.state;
this.props.onSave({
callWith,
myLocation,
ringoutPrompt,
});
}
}
onReset = () => {
const {
callWith,
myLocation,
ringoutPrompt,
} = this.props;
this.setState({
callWith,
myLocation,
ringoutPrompt,
});
}
onCallWithChange = (callWith) => {
this.setState({
callWith,
myLocation: (this.props.availableNumbers[callWith] &&
this.props.availableNumbers[callWith][0]) ||
'',
});
}
onMyLocationChange = (myLocation) => {
this.setState({
myLocation
});
}
onRingoutPromptChange = (checked) => {
this.setState({
ringoutPrompt: checked,
});
}
renderHandler = (option) => {
const brand = this.props.brand;
return formatMessage(i18n.getString(option, this.props.currentLocale), { brand });
}
render() {
const {
currentLocale,
callWith,
callWithOptions,
myLocation,
ringoutPrompt,
onBackButtonClick,
brand,
availableNumbers,
className,
} = this.props;
const buttons = [];
const hasChanges = this.state.callWith !== callWith ||
this.state.myLocation !== myLocation ||
this.state.ringoutPrompt !== ringoutPrompt;
buttons.push({
label: <i className="fa fa-undo" />,
onClick: this.onReset,
placement: 'right',
hidden: !hasChanges,
});
buttons.push({
label: <i className="fa fa-floppy-o" />,
onClick: this.onSave,
placement: 'right',
disabled: !hasChanges,
});
const ringout = this.state.callWith !== callingOptions.softphone ? (
<div>
<div className={styles.ringoutHint}>
{i18n.getString('ringoutHint', currentLocale)}
</div>
<InputField
className={styles.inputField}
label={i18n.getString('myLocationLabel', currentLocale)}>
{
availableNumbers[this.state.callWith] ? (
<Select
className={styles.select}
value={this.state.myLocation}
onChange={this.onMyLocationChange}
options={availableNumbers[this.state.callWith]}
dropdownAlign="left"
/>
) : (
<TextInput
value={this.state.myLocation}
maxLength={30}
onChange={this.onMyLocationChange} />
)
}
</InputField>
<IconField
className={styles.iconField}
icon={
<Switch
checked={this.state.ringoutPrompt}
onChange={this.onRingoutPromptChange}
/>
}
>
{i18n.getString('press1ToStartCallLabel', currentLocale)}
</IconField>
</div>
) : null;
return (
<div className={classnames(styles.root, className)}>
<BackHeader
buttons={buttons}
onBackClick={onBackButtonClick}
>
{i18n.getString('title', currentLocale)}
</BackHeader>
<Panel className={styles.content}>
<InputField
className={styles.inputField}
label={i18n.getString('makeCallsWith', currentLocale)} noBorder>
<Select
className={styles.select}
value={this.state.callWith}
onChange={this.onCallWithChange}
options={callWithOptions}
dropdownAlign="left"
renderValue={this.renderHandler}
renderFunction={this.renderHandler}
/>
</InputField>
{ringout}
</Panel>
</div>
);
}
}
CallingSettingsPanel.propTypes = {
brand: PropTypes.string.isRequired,
className: PropTypes.string,
currentLocale: PropTypes.string.isRequired,
callWithOptions: PropTypes.arrayOf(PropTypes.string).isRequired,
callWith: PropTypes.string.isRequired,
myLocation: PropTypes.string.isRequired,
ringoutPrompt: PropTypes.bool.isRequired,
availableNumbers: PropTypes.object.isRequired,
onBackButtonClick: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired,
};
|
ajax/libs/angular.js/1.0.7/angular-scenario.js | ruiaraujo/cdnjs | /*!
* 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 strict';
// 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 );
/**
* @license AngularJS v1.0.7
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document){
var _jQuery = window.jQuery.noConflict(true);
////////////////////////////////////
/**
* @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) {
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
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 = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...)
*/
function isArrayLike(obj) {
if (!obj || (typeof obj.length !== 'number')) return false;
// We have on object which has length property. Should we treat it as array?
if (typeof obj.hasOwnProperty != 'function' &&
typeof obj.constructor != 'function') {
// This is here for IE8: it is a bogus object treat it as array;
return true;
} else {
return obj instanceof JQLite || // JQLite
(jQuery && obj instanceof jQuery) || // jQuery
toString.call(obj) !== '[object Object]' || // some browser native object
typeof obj.callee === 'function'; // arguments (on IE8 looks like regular 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 || 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';}
/**
* 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';
}
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : 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.bind && node.find)); // we have a bind 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 size = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
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, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @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.
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw Error("Can't copy equivalent objects or arrays");
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) {
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, 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 pass `===` comparison.
* * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
*
* During a property comparision, 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 ((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 (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(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[key] &&
key.charAt(0) !== '$' &&
o2[key] !== undefined &&
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @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 [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @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.
*/
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 (/^\$+/.test(key)) {
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.
*
* @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} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
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);
}
}
/////////////////////////////////////////////////
/**
* 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 = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too agressive 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 becuase encodeURIComponent is too agressive 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 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.
*
* In the example below if the `ngApp` directive would not be 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}
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
var resumeBootstrapInternal = function() {
element = jqLite(element);
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function(scope, element, compile, injector) {
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 resumeBootstrapInternal();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
resumeBootstrapInternal();
};
}
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,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
JQLitePatchJQueryRemove('remove', true);
JQLitePatchJQueryRemove('empty');
JQLitePatchJQueryRemove('html');
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw new Error("Argument '" + (name || '?') + "' is " + (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;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
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 and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configuration information. 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#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + 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#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} name Controller name.
* @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} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#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;
}
}
});
};
});
}
/**
* @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.0.7', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: 0,
dot: 7,
codeName: 'monochromatic-rainbow'
};
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}
});
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,
ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$route: $RouteProvider,
$routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following 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/bind/) - Does not support namespaces
* - [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
* - [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/) - Doesn't pass native event objects to handlers.
* - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## In addtion to the above, Angular provides additional methods to both jQuery and jQuery lite:
*
* - `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.
* - `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])/;
/**
* 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) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch() {
var list = [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children,
fns, events;
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 Error('selectors not implemented');
}
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);
this.remove(); // 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 JQLiteUnbind(element, type, fn) {
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 {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type], fn);
}
}
}
function JQLiteRemoveData(element) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
JQLiteUnbind(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) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function JQLiteRemoveClass(element, cssClasses) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, cssClasses) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
}
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');
}
while (element.length) {
if (value = element.data(name)) 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();
}
this.bind('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.
JQLite(window).bind('load', trigger); // fallback to window.onload for others
},
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'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form'.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) {
return JQLiteInheritedData(element, '$scope');
},
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: extend((msie < 9)
? function(element, value) {
if (element.nodeType == 1 /** Element */) {
if (isUndefined(value))
return element.innerText;
element.innerText = value;
} else {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue = value;
}
}
: function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent = value;
}, {$dv:''}),
val: function(element, value) {
if (isUndefined(value)) {
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.
if (this.length)
return fn(this[0], arg1, arg2);
}
} 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;
}
return fn.$dv;
};
});
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;
};
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,
bind: function bindFn(element, type, fn){
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 ) {
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"}
bindFn(element, eventmap[type], function(event) {
var ret, 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);
});
},
unbind: JQLiteUnbind,
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.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index = child;
}
});
}
},
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) {
var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName];
forEach(eventFns, function(fn) {
fn.call(element, null);
});
}
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2) {
var value;
for(var i=0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value == undefined ? this : value;
};
});
/**
* 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;
}
};
/**
* A map where multiple values can be added to the same key such that they form a queue.
* @returns {HashQueueMap}
*/
function HashQueueMap() {}
HashQueueMap.prototype = {
/**
* Same as array push, but using an array as the value for the hash
*/
push: function(key, value) {
var array = this[key = hashKey(key)];
if (!array) {
this[key] = [value];
} else {
array.push(value);
}
},
/**
* Same as array shift, but using an array as the value for the hash
*/
shift: function(key) {
var array = this[key = hashKey(key)];
if (array) {
if (array.length == 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
},
/**
* return the first item without deleting it
*/
peek: function(key) {
var array = this[hashKey(key)];
if (array) {
return array[0];
}
}
};
/**
* @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;
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
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. The function arguments come form the function annotation.
* @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#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 minfication / 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
*
* Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
* The providers share the same name as the instance they create with `Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow for configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation = 'Hello';
*
* this.salutation = function(text) {
* salutation = text;
* };
*
* this.$get = function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* }));
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
*
* @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
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @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
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
* into configuration function (other modules) and it is not interceptable by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service instance creation. The
* returned instance may be the original instance, or a new instance which delegates to the
* original instance.
*
* @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. 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.
*/
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 = createInternalInjector(providerCache, function() {
throw Error("Unknown provider: " + 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_) {
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.');
}
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, value) { return factory(name, valueFn(value)); }
function constant(name, value) {
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 = [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
if (isString(module)) {
var moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
try {
for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = invokeArgs[0] == '$injector'
? providerInjector
: providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isFunction(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isArray(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + String(module[module.length - 1]);
throw e;
}
} else {
assertArgFn(module, 'module');
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (typeof serviceName !== 'string') {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw Error('Circular dependency: ' + 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];
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) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate
};
}
}
/**
* @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 scroll whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*/
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;
}];
}
/**
* ! 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');
/**
* @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) {
// 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 {
if (replace) location.replace(url);
else location.href = url;
}
return self;
// getter
} else {
// the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
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).bind('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
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 Cokkie 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:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
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
var 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 defered.
* @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 asynchroniously 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 defered 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 successfuly 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.
*
*
* @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.
* - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache.
* - `{{*}}` `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 Error('cacheId ' + cacheId + ' taken');
}
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);
}
},
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
}
}
}
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* Cache used for storing html templates.
*
* 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)
*/
var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
/**
* @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 trying to match DOM elements to
* {@link ng.$compileProvider#directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original template.
*
<doc:example module="compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
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.
*/
/**
* @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\-_]+)(?:\:([^;]+))?;?)/,
MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ',
urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/;
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directives with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more
* info.
* @returns {ng.$compileProvider} Self for chaining.
*/
this.directive = function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directive');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory) {
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.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#urlSanitizationWhitelist
* @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 `urlSanitizationWhitelist` 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 it is 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.urlSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
urlSanitizationWhitelist = regexp;
return this;
}
return urlSanitizationWhitelist;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope', '$document',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope, $document) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* 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) {
var booleanKey = getBooleanAttrName(this.$$element[0], key),
$$observers = this.$$observers,
normalizedVal;
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, '-');
}
}
// sanitize a[href] values
if (nodeName_(this.$$element[0]) === 'A' && key === 'href') {
urlSanitizationNode.setAttribute('href', value);
// href property always returns normalized absolute url, so we can match against that
normalizedVal = urlSanitizationNode.href;
if (!normalizedVal.match(urlSanitizationWhitelist)) {
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
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not interpolated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$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 urlSanitizationNode = $document[0].createElement('a'),
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
? identity
: function denormalizeTemplate(template) {
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
};
return compile;
//================================
function compile($compileNodes, transcludeFn, maxPriority) {
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] = jqLite(node).wrap('<span></span>').parent()[0];
}
});
var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority);
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 wrongMode(localName, mode) {
throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
}
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) {
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, maxPriority);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
: 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);
}
// 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, 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++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new(isObject(nodeLinkFn.scope));
jqLite(node).data('$scope', childScope);
} 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).
bind('$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) {
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);
// iterate over the attributes
for (var attr, name, nName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
attr = nAttrs[j];
if (attr.specified) {
name = attr.name;
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);
}
}
// 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)) {
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)) {
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;
}
/**
* 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.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) {
var terminalPriority = -Number.MAX_VALUE,
preLinkFns = [],
postLinkFns = [],
newScopeDirective = null,
newIsolateScopeDirective = null,
templateDirective = null,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
transcludeDirective,
childTranscludeFn = transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolateScopeDirective = directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (directiveValue = directive.controller) {
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
terminalPriority = directive.priority;
if (directiveValue == 'element') {
$template = jqLite(compileNode);
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' '));
compileNode = $compileNode[0];
replaceWith(jqCollection, jqLite($template[0]), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority);
} else {
$template = jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if ((directiveValue = directive.template)) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
directiveValue = denormalizeTemplate(directiveValue);
if (directive.replace) {
$template = jqLite('<div>' +
trim(directiveValue) +
'</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
}
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 were already applied and those that weren't
// - collect directives from the template, add them to the second group and sort them
// - append the second group with new directives to the first group
directives = directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length - (i + 1)),
newTemplateAttrs
)
);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace,
childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post) {
if (pre) {
pre.require = directive.require;
preLinkFns.push(pre);
}
if (post) {
post.require = directive.require;
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 (!value && !optional) {
throw Error("No controller: " + require);
}
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;
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 parentScope = scope.$parent || scope;
forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) {
var match = definiton.match(LOCAL_REGEXP) || [],
attrName = match[2]|| scopeName,
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
scope.$$isolateBindings[scopeName] = mode + attrName;
switch (mode) {
case '@': {
attrs.$observe(attrName, function(value) {
scope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = parentScope;
break;
}
case '=': {
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
' (directive: ' + newIsolateScopeDirective.name + ')');
};
lastValue = scope[scopeName] = parentGet(parentScope);
scope.$watch(function parentValueWatch() {
var parentValue = parentGet(parentScope);
if (parentValue !== scope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !== lastValue) {
// parent changed and it has precedence
lastValue = scope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, parentValue = lastValue = scope[scopeName]);
}
}
return parentValue;
});
break;
}
case '&': {
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(parentScope, locals);
};
break;
}
default: {
throw Error('Invalid isolate scope definition for directive ' +
newIsolateScopeDirective.name + ': ' + definiton);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
};
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
$element.data(
'$' + directive.name + 'Controller',
$controller(controller, locals));
});
}
// PRELINKING
for(i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for(i = 0, ii = postLinkFns.length; i < ii; i++) {
try {
linkFn = postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* 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) {
var match = false;
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) {
tDirectives.push(directive);
match = true;
}
} 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);
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
$rootElement, replace, childTranscludeFn) {
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, {
controller: null, templateUrl: null, transclude: null, scope: null
});
$compileNode.html('');
$http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
content = denormalizeTemplate(content);
if (replace) {
$template = jqLite('<div>' + trim(content) + '</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives, tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn);
afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
while(linkQueue.length) {
var controller = linkQueue.pop(),
linkRootElement = linkQueue.pop(),
beforeTemplateLinkNode = linkQueue.pop(),
scope = linkQueue.pop(),
linkNode = compileNode;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
}, scope, linkNode, $rootElement, controller);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw Error('Failed to load template: ' + 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(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw Error('Multiple directives [' + previousDirective.name + ', ' +
directive.name + '] asking for ' + what + ' on: ' + 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 addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
directives.push({
priority: 100,
compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (name === 'class') {
// we need to interpolate classes again, in the case the element was replaced
// and therefore the two class attrs got merged - we want to interpolate the result
interpolateFn = $interpolate(attr[name], true);
}
attr[name] = undefined;
($$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} $element 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, $element, newNode) {
var oldNode = $element[0],
parent = oldNode.parentNode,
i, ii;
if ($rootElement) {
for(i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == oldNode) {
$rootElement[i] = newNode;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, oldNode);
}
newNode[jqLite.expando] = oldNode[jqLite.expando];
$element[0] = newNode;
}
}];
}
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 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.
*/
/**
* 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#register register} method.
*/
function $ControllerProvider() {
var controllers = {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
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(constructor, locals) {
if(isString(constructor)) {
var name = constructor;
constructor = controllers.hasOwnProperty(name)
? controllers[name]
: getter(locals.$scope, name, true) || getter($window, name, true);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}];
}
/**
* @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.
*
* @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);
};
}];
}
/**
* @ngdoc object
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*/
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', function($parse) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
*
* @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.
* @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) {
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;
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
};
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;
}];
}
var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH = PATH_MATCH,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
/**
* 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 stripHash(url) {
return url.split('#')[0];
}
function matchUrl(url, obj) {
var match = URL_MATCH.exec(url);
match = {
protocol: match[1],
host: match[3],
port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol = match.protocol;
obj.$$host = match.host;
obj.$$port = match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
match.hash.indexOf(hashPrefix) !== 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) +
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) == basePath && !isUndefined(match.hash) &&
match.hash.indexOf(hashPrefix) === 0) {
return url;
// convert html5 url -> hashbang url
} else {
var search = match.search && '?' + match.search || '',
hash = match.hash && '#' + match.hash || '',
pathPrefix = pathPrefixFromBase(basePath),
path = match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
}
return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} url HTML5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix, appBaseUrl) {
pathPrefix = pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(newAbsoluteUrl) {
var match = matchUrl(newAbsoluteUrl, this);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
}
this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
this.$$search = parseKeyValue(match.search);
this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
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 = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
pathPrefix + this.$$url;
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is disabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and search)
*/
function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
}
basePath = match.path + (match.search ? '?' + match.search : '');
match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
if (match[1]) {
this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
} else {
this.$$path = '';
}
this.$$search = parseKeyValue(match[3]);
this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
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 = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
LocationUrl.prototype = {
/**
* 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`)
* @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,string>=} search New search params - string or hash object
* @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If the value is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
} else {
this.$$search = isString(search) ? parseKeyValue(search) : search;
}
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;
}
};
LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
LocationHashbangUrl.apply(this, arguments);
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
}
}
}
LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
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 {string=} 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;
}
};
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
basePath,
pathPrefix,
initUrl = $browser.url(),
initUrlParts = matchUrl(initUrl),
appBaseUrl;
if (html5Mode) {
basePath = $browser.baseHref() || '/';
pathPrefix = pathPrefixFromBase(basePath);
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
pathPrefix + '/';
if ($sniffer.history) {
$location = new LocationUrl(
convertToHtml5Url(initUrl, basePath, hashPrefix),
pathPrefix, appBaseUrl);
} else {
$location = new LocationHashbangInHtml5Url(
convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
}
} else {
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
(initUrlParts.path || '') +
(initUrlParts.search ? ('?' + initUrlParts.search) : '') +
'#' + hashPrefix + '/';
$location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
}
$rootElement.bind('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'),
rewrittenUrl = $location.$$rewriteAppUrl(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
event.preventDefault();
// 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() != initUrl) {
$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 writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @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>
*/
function $LogProvider(){
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#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
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);
}
}
}];
}
var OPERATORS = {
'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|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, csp){
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2];
if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName, ch;
while (index < text.length) {
ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while(peekIndex < text.length) {
ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
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) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
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.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain =
function() { throwError("is not valid json", {text:text, index:0}); };
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self, locals) {
return fn(self, locals, right);
};
}
function binaryFn(left, fn, right) {
return function(self, locals) {
return fn(self, locals, left, right);
};
}
function statements() {
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!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;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while(true) {
if ((token = expect(':'))) {
argsFn.push(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;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = logicalOR();
return function(scope, locals){
return left.assign(scope, right(scope, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==','!='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp);
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);
}
}
);
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function(self, locals){
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = o[i];
if (v && v.then) {
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){
return obj(self, locals)[indexFn(self, locals)] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(scope, locals){
var args = [],
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;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
if (peekToken().text != ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function(self, locals){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
};
}
function object () {
var keyValues = [];
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
} while (expect(','));
}
consume('}');
return 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;
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accesible 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 accesbile 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;
}
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) {
return function(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) {
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) {
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) {
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) {
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) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
}
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
: function(scope, locals) {
var i = 0, val;
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
)(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) {
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' +
'if (s && s.then) {\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;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() { return code; };
}
return getterFnCache[path] = 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 (tipically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The return function also has an `assign` property, if the expression is assignable, which
* allows one to set values to expressions.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] = parser(exp, false, $filter, $sniffer.csp);
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() {
* 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);
* });
* </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](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 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`.
*
* **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)` – regardless of when the promise was or will be resolved
* or rejected 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.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback` or `errorCallback`.
*
*
* # Chaining promises
*
* Because calling `then` api 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 promises are recognized by the templating engine in angular, which means that in templates
* you can treat promises attached to a scope as if they were the resulting values.
* - 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]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
promise: {
then: function(callback, errback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((callback || defaultCallback)(value));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((errback || defaultErrback)(reason));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback]);
} else {
value.then(wrappedCallback, wrappedErrback);
}
return result.promise;
}
}
};
return deferred;
};
var ref = function(value) {
if (value && 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() {
result.resolve((errback || defaultErrback)(reason));
});
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) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
});
});
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>} promises An array of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value corresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
function all(promises) {
var deferred = defer(),
counter = promises.length,
results = [];
if (counter) {
forEach(promises, function(promise, index) {
ref(promise).then(function(value) {
if (index in results) return;
results[index] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (index in results) return;
deferred.reject(reason);
});
});
} else {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* @ngdoc object
* @name ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link ng.$route $route} for an example.
*/
function $RouteProvider(){
var routes = {};
/**
* @ngdoc method
* @name ng.$routeProvider#when
* @methodOf ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exactly match the
* route definition.
*
* `path` can contain named groups starting with a colon (`:name`). All characters up to the
* next slash are matched and stored in `$routeParams` under the given `name` when the route
* matches.
*
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly
* created scope or the name of a {@link angular.Module#controller registered controller}
* if passed as a string.
* - `template` – `{string=}` – html template as a string that should be used by
* {@link ng.directive:ngView ngView} or
* {@link ng.directive:ngInclude ngInclude} directives.
* this property takes precedence over `templateUrl`.
* - `templateUrl` – `{string=}` – path to an html template that should be used by
* {@link ng.directive:ngView ngView}.
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, they will be
* resolved and converted to a value before the controller is instantiated and the
* `$routeChangeSuccess` event is fired. The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is resolved
* before its value is injected into the controller.
*
* - `redirectTo` – {(string|function())=} – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
routes[path] = extend({reloadOnSearch: true}, route);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length-1] == '/')
? path.substr(0, path.length-1)
: path +'/';
routes[redirectPath] = {redirectTo: path};
}
return this;
};
/**
* @ngdoc method
* @name ng.$routeProvider#otherwise
* @methodOf ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
* @returns {Object} self
*/
this.otherwise = function(params) {
this.when(null, params);
return this;
};
this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) {
/**
* @ngdoc object
* @name ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
* directive and the {@link ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link ng.directive:script inlined templates}
to get it working on jsfiddle as well.
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeStart
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occurs.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeSuccess
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ng.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} current Current route information.
* @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeError
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name ng.$route#$routeUpdate
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var forceReload = false,
$route = {
routes: routes,
/**
* @ngdoc method
* @name ng.$route#reload
* @methodOf ng.$route
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ng.directive:ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
forceReload = true;
$rootScope.$evalAsync(updateRoute);
}
};
$rootScope.$on('$locationChangeSuccess', updateRoute);
return $route;
/////////////////////////////////////////////////////
/**
* @param on {string} current url
* @param when {string} route when template to match the url against
* @return {?Object}
*/
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should construct the route matching
// regex only once and then reuse it
// Escape regexp special characters.
when = '^' + when.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") + '$';
var regex = '',
params = [],
dst = {};
var re = /:(\w+)/g,
paramMatch,
lastMatchedIndex = 0;
while ((paramMatch = re.exec(when)) !== null) {
// Find each :param in `when` and replace it with a capturing group.
// Append all other sections of when unchanged.
regex += when.slice(lastMatchedIndex, paramMatch.index);
regex += '([^\\/]*)';
params.push(paramMatch[1]);
lastMatchedIndex = re.lastIndex;
}
// Append trailing path part.
regex += when.substr(lastMatchedIndex);
var match = on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] = match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$$route === last.$$route
&& equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
last.params = next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload = false;
$rootScope.$broadcast('$routeChangeStart', next, last);
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
.replace();
}
}
}
$q.when(next).
then(function() {
if (next) {
var keys = [],
values = [],
template;
forEach(next.resolve || {}, function(value, key) {
keys.push(key);
values.push(isString(value) ? $injector.get(value) : $injector.invoke(value));
});
if (isDefined(template = next.template)) {
} else if (isDefined(template = next.templateUrl)) {
template = $http.get(template, {cache: $templateCache}).
then(function(response) { return response.data; });
}
if (isDefined(template)) {
keys.push('$template');
values.push(template);
}
return $q.all(values).then(function(values) {
var locals = {};
forEach(values, function(value, index) {
locals[keys[index]] = value;
});
return locals;
});
}
}).
// after route change
then(function(locals) {
if (next == $route.current) {
if (next) {
next.locals = locals;
copy(next.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', next, last);
}
}, function(error) {
if (next == $route.current) {
$rootScope.$broadcast('$routeChangeError', next, last, error);
}
});
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = switchRouteMatcher($location.path(), path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string||'').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
/**
* @ngdoc object
* @name ng.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination of the
* {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
* are extracted when the {@link ng.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get = valueFn({});
}
/**
* 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.
*
* @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 child scopes of the root scope. Scopes provide mechanism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider(){
var TTL = 10;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse',
function( $injector, $exceptionHandler, $parse) {
/**
* @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#$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>
angular.injector(['ng']).invoke(function($rootScope) {
var scope = $rootScope.$new();
scope.salutation = 'Hello';
scope.name = 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function() {
scope.greeting = scope.salutation + ' ' + scope.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name = 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
});
* </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.$$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 = {
/**
* @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 (isFunction(isolate)) {
// TODO: remove at some point
throw Error('API-CHANGE: Use $controller to instantiate controllers.');
}
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These 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.$$asyncQueue = [];
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 which 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.
*
*
* # 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);
* </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 (!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#$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#directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
* {@link ng.$compileProvider#directive directives}) 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`.
*
* You may have a need to call `$digest()` from within unit-tests, 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,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg;
beginPhase('$digest');
do {
dirty = false;
current = target;
do {
asyncQueue = current.$$asyncQueue;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
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 ((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 Error(TTL + ' $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @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.
*/
/**
* @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 chance to
* perform any necessary cleanup.
*/
$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 returning 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.
*
* @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 in the current script execution context (before any 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.
*
* @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) {
this.$$asyncQueue.push(expr);
},
/**
* @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 {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//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 emmited 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 Error($rootScope.$$phase + ' already in progress');
}
$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() {}
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', function($window) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
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
history: !!($window.history && $window.history.pushState && !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.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 = $window.document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without triggering alerts
csp: false
};
}];
}
/**
* @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 overriden, removed or mocked for testing.
*
* All expressions are evaluated with respect to current scope so they don't
* suffer from window globality.
*
* @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);
}
/**
* 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/;
var $config = 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, true);
}
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, */*',
'X-Requested-With': 'XMLHttpRequest'
},
post: {'Content-Type': 'application/json;charset=utf-8'},
put: {'Content-Type': 'application/json;charset=utf-8'}
}
};
var providerResponseInterceptors = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http'),
responseInterceptors = [];
forEach(providerResponseInterceptors, function(interceptor) {
responseInterceptors.push(
isString(interceptor)
? $injector.get(interceptor)
: $injector.invoke(interceptor)
);
});
/**
* @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.
*
* # 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#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#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, * / *`
* - `X-Requested-With: XMLHttpRequest`
* - `$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'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same
* fashion.
*
*
* # 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.
*
*
* # Response 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 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
* }, 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
* called `XSRF-TOKEN` and sets it as the 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.
*
* 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.
*
*
* @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 representing HTTP headers to send to the server.
* - **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}` – timeout in milliseconds.
* - **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.
*
* @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(config) {
config.method = uppercase(config.method);
var reqTransformFn = config.transformRequest || $config.transformRequest,
respTransformFn = config.transformResponse || $config.transformResponse,
defHeaders = $config.headers,
reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']},
defHeaders.common, defHeaders[lowercase(config.method)], config.headers),
reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn),
promise;
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
// send request
promise = sendReq(config, reqData, reqHeaders);
// transform future response
promise = promise.then(transformResponse, transformResponse);
// apply interceptors
forEach(responseInterceptors, function(interceptor) {
promise = interceptor(promise);
});
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, respTransformFn)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
}
$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 as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = $config;
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, $config, $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 && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache : defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (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 (!cachedResp) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials);
}
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);
$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 || value == undefined) return;
if (isObject(value)) {
value = toJson(value);
}
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
}];
}
var XHR = window.XMLHttpRequest || function() {
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 new Error("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) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
var status;
// 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();
// TODO(vojta): remove once Firefox 21 gets released.
// begin: workaround to overcome Firefox CORS http response headers bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=608735
// Firefox already patched in nightly. Should land in Firefox 21.
// CORS "simple response headers" http://www.w3.org/TR/cors/
var value,
simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type",
"Expires", "Last-Modified", "Pragma"];
if (!responseHeaders) {
responseHeaders = "";
forEach(simpleHeaders, function (header) {
var value = xhr.getResponseHeader(header);
if (value) {
responseHeaders += header + ": " + value + "\n";
}
});
}
// end of the workaround.
completeRequest(callback, status || xhr.status, xhr.responseText,
responseHeaders);
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
xhr.send(post || '');
if (timeout > 0) {
$browserDefer(function() {
status = -1;
xhr.abort();
}, timeout);
}
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1];
// 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);
}
}
/**
* @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';
}
};
};
}
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#$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.
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup = function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
promise.then(cleanup, cleanup);
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');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
/**
* @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 suffixe 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/dev_guide.templates.filters Understanding Angular 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';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}];
////////////////////////////////////////
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.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @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.
*
* @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'}]"></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>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:search">
<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']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression) {
if (!isArray(array)) return array;
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
var search = function(obj, text){
if (text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
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":
expression = {$:expression};
case "object":
for (var key in expression) {
if (key == '$') {
(function() {
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function() {
var path = key;
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
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=2] Number of decimal places to round the number to.
* @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 pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var 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);
}
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),
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)
* * `'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))?)?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
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 containing only a specified number of elements in an array. The elements
* are taken from either the beginning or the end of the source array, as specified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `limit` number is
* positive, `limit` number of items from the beginning of the source array are copied.
* If the number is negative, `limit` number of items from the end of the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array 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.limit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="limit">
<p>Output: {{ numbers | limitTo:limit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit = int(limit);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more informaton about Angular arrays.
*
* @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();
if (t1 == "string") 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 html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* `<a href="" ng-click="model.$save()">Save</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.bind('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 makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy 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 uses `link` variable inside `href` attribute:
<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: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 specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @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 Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @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 Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngMultiple
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngMultiple` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
<select id="select" ng-multiple="checked">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element SELECT
* @param {expression} ngMultiple Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @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 {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @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 {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
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-href are interpolated
forEach(['src', '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]);
});
}
};
};
});
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: 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 = {};
// init state
form.$name = attrs.name;
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);
}
form.$addControl = function(control) {
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] = control;
}
};
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);
});
};
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;
}
};
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
parentForm.$setDirty();
};
}
/**
* @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=} name|ngForm 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 `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, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # 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 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 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 ngSubmit or ngClick directives. This
* is because of the following form submission rules coming from the html spec:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has 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: '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.bind('$destroy', function() {
$timeout(function() {
removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
}, 0, false);
});
}
var parentFormCtrl = formElement.parent().controller('form'),
alias = attr.name || attr.ngForm;
if (alias) {
scope[alias] = controller;
}
if (parentFormCtrl) {
formElement.bind('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
scope[alias] = undefined;
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective;
}];
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
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,4}$/;
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.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\w*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required>
<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');
});
</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.list.$error.required">
Required!</span>
<span class="error" ng-show="myForm.list.$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.
*
* @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 isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = trim(element.val());
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.bind('input', listener);
} else {
var timeout;
var deferListener = function() {
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
};
element.bind('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.bind('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.bind('paste cut', deferListener);
}
}
ctrl.$render = function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator;
var validate = function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
if (pattern.match(/^\/(.*)\/$/)) {
pattern = new RegExp(pattern.substr(1, pattern.length - 2));
patternValidator = function(value) {
return validate(pattern, value)
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
}
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 (!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 (!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 = 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 isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min = parseFloat(attr.min);
var minValidator = function(value) {
if (!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 max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!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 (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 (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 (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.bind('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.bind('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
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 Whenever the control reads value from the DOM, it executes
* all of these functions to sanitize / convert the value as well as validate.
*
* @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
* these functions to convert the value as well as validate.
*
* @property {Object} $error An bject 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 update, value formatting and parsing. It
* specifically does not contain any logic which deals with DOM rendering or listening to
* DOM events. The `NgModelController` is meant to be extended by other directives where, the
* directive provides DOM manipulation and the `NgModelController` provides the data-binding.
*
* 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.
*
* <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.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
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>
*
*/
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 Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $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;
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) {
if ($error[validationErrorKey] === !isValid) return;
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#$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` and if resulted value is valid, updates the model and
* 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
* Is directive that tells Angular to do two-way data binding. It works together with `input`,
* `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
*
* `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 state of the control (valid/invalid, dirty/pristine, validation errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* 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);
element.bind('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @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
*
* @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 && (isEmpty(value) || value === false)) {
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 comma-separated string into an array of strings.
*
* @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.list.$error.required">
Required!</span>
<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');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
});
</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) {
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;
});
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
attr.$set('value', value, false);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @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.
*
* One scenario in which the use of `ngBind` is preferred over `{{ expression }}` binding is when
* it's desirable to put bindings into template that 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) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text should be replaced with the template in ngBindTemplate.
* Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @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:ngBindHtmlUnsafe
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
* {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
* restrictive and when you absolutely trust the source of the content you are binding to.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlUnsafeDirective = [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
var oldVal = undefined;
scope.$watch(attr[name], ngClassWatchAction, true);
attr.$observe('class', function(value) {
var ngClass = scope.$eval(attr[name]);
ngClassWatchAction(ngClass, ngClass);
});
if (name !== 'ngClass') {
scope.$watch('$index', function($index, old$index) {
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) {
if (isObject(classVal) && !isArray(classVal)) {
classVal = map(classVal, function(v, k) { if (v) return k });
}
element.removeClass(isArray(classVal) ? classVal.join(' ') : classVal);
}
function addClass(classVal) {
if (isObject(classVal) && !isArray(classVal)) {
classVal = map(classVal, function(v, k) { if (v) return k });
}
if (classVal) {
element.addClass(isArray(classVal) ? classVal.join(' ') : classVal);
}
}
});
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS class on HTML element dynamically 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.
*
* @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.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.my-class {
color: red;
}
</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>
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a 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
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a 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
*
* @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 typically a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser view.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* 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 `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 assigns behavior to a scope. 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 data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the {@link ng.$route $route} service.
*
* @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.
*
* @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.
<doc:example>
<doc:source>
<script>
function SettingsController($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 ng-controller="SettingsController">
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('.doc-example-live div>:input').val()).toBe('John Smith');
expect(element('.doc-example-live li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li:nth-child(2) input').val())
.toBe('[email protected]');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('');
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live 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
* @priority 1000
*
* @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. By applying `ngCsp`
* it is be possible to opt into the CSP compatible 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.
*
* In order to use this feature put `ngCsp` directive on the root element of the application.
*
* @example
* This example shows how to apply the `ngCsp` directive to the `html` tag.
<pre>
<!doctype html>
<html ng-app ng-csp>
...
...
</html>
</pre>
*/
var ngCspDirective = ['$sniffer', function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp = true;
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* 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'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.bind(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 dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* dblclick. (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: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).
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
*
* @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>
*/
var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
element.bind('submit', function() {
scope.$apply(attrs.ngSubmit);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
* file:// access on some browsers).
*
* @scope
*
* @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>
<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 ng-include src="template.url"></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="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]').text()).toEqual('');
});
</file>
</example>
*/
/**
* @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',
function($http, $templateCache, $anchorScroll, $compile) {
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, element) {
var changeCounter = 0,
childScope;
var clearContent = function() {
if (childScope) {
childScope.$destroy();
childScope = null;
}
element.html('');
};
scope.$watch(srcExp, function ngIncludeWatchAction(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
if (childScope) childScope.$destroy();
childScope = scope.$new();
element.html(response);
$compile(element.contents())(childScope);
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter) clearContent();
});
} else clearContent();
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</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
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple 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 and the rules 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 pural 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. You will see the use of plural categories
* and explicit number rules throughout later parts 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 so that Angular
* can interpret it correctly.
*
* 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 correspoding 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 = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp),
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol();
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:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
* * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
* * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
*
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
* 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: `track in cd.tracks`.
*
* * `(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}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng-repeat', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
var ngRepeatDirective = ngDirective({
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function(scope, iterStartElement, attr){
var expression = attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
lhs + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = 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 an array of objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
// We need an array of these objects since the same object can be returned from the iterator.
// We expect this to be a rare case.
var lastOrder = new HashQueueMap();
scope.$watch(function ngRepeatWatch(scope){
var index, length,
collection = scope.$eval(rhs),
cursor = iterStartElement, // current position of the node
// Same as lastOrder but it has the current state. It will become the
// lastOrder on the next iteration.
nextOrder = new HashQueueMap(),
arrayBound,
childScope,
key, value, // key/value of iteration
array,
last; // last object information {scope, element, index}
if (!isArray(collection)) {
// if object, extract keys, sort them and use to determine order of iteration over obj props
array = [];
for(key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
array.push(key);
}
}
array.sort();
} else {
array = collection || [];
}
arrayBound = array.length-1;
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = array.length; index < length; index++) {
key = (collection === array) ? index : array[index];
value = collection[key];
last = lastOrder.shift(value);
if (last) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = last.scope;
nextOrder.push(value, last);
if (index === last.index) {
// do nothing
cursor = last.element;
} else {
// existing item which got moved
last.index = index;
// This may be a noop, if the element is next, but I don't know of a good way to
// figure this out, since it would require extra DOM access, so let's just hope that
// the browsers realizes that it is noop, and treats it as such.
cursor.after(last.element);
cursor = last.element;
}
} else {
// new item which we don't know about
childScope = scope.$new();
}
childScope[valueIdent] = value;
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === arrayBound);
childScope.$middle = !(childScope.$first || childScope.$last);
if (!last) {
linker(childScope, function(clone){
cursor.after(clone);
last = {
scope: childScope,
element: (cursor = clone),
index: index
};
nextOrder.push(value, last);
});
}
}
//shrink children
for (key in lastOrder) {
if (lastOrder.hasOwnProperty(key)) {
array = lastOrder[key];
while(array.length) {
value = array.pop();
value.element.remove();
value.scope.$destroy();
}
}
}
lastOrder = nextOrder;
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/>
Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
</doc:source>
<doc:scenario>
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);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngShowDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngShow, function ngShowWatchAction(value){
element.css('display', toBoolean(value) ? '' : 'none');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` and `ngShow` directives hide or show a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</doc:source>
<doc:scenario>
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);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngHideDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngHide, function ngHideWatchAction(value){
element.css('display', toBoolean(value) ? 'none' : '');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @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
* Conditionally change the DOM structure.
*
* @usage
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* ...
* <ANY ng-switch-default>...</ANY>
* </ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed.
* * `ngSwitchDefault`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</script>
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
</div>
</doc:source>
<doc:scenario>
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 deafault', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</doc:scenario>
</doc:example>
*/
var NG_SWITCH = 'ng-switch';
var ngSwitchDirective = valueFn({
restrict: 'EA',
require: 'ngSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope', function ngSwitchController() {
this.cases = {};
}],
link: function(scope, element, attr, ctrl) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTransclude,
selectedElement,
selectedScope;
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement = selectedScope = null;
}
if ((selectedTransclude = ctrl.cases['!' + value] || ctrl.cases['?'])) {
scope.$eval(attr.change);
selectedScope = scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement = caseElement;
element.append(caseElement);
});
}
});
}
});
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 500,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['!' + attrs.ngSwitchWhen] = transclude;
};
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 500,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['?'] = transclude;
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @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: 'isolate',
locals: { title:'bind' },
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: ['$transclude', '$element', function($transclude, $element) {
$transclude(function(clone) {
$element.append(clone);
});
}]
});
/**
* @ngdoc directive
* @name ng.directive:ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ng.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* @scope
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngView#$viewContentLoaded
* @eventOf ng.directive:ngView
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
'$controller',
function($http, $templateCache, $route, $anchorScroll, $compile,
$controller) {
return {
restrict: 'ECA',
terminal: true,
link: function(scope, element, attr) {
var lastScope,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope = null;
}
}
function clearContent() {
element.html('');
destroyLastScope();
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (template) {
element.html(template);
destroyLastScope();
var link = $compile(element.contents()),
current = $route.current,
controller;
lastScope = current.scope = scope.$new();
if (current.controller) {
locals.$scope = lastScope;
controller = $controller(current.controller, locals);
element.children().data('$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
// $anchorScroll might listen on event...
$anchorScroll();
} else {
clearContent();
}
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:script
*
* @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.
*
* @restrict E
* @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);
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for a `<select>` element using an array or an object obtained by evaluating the
* `ngOptions` expression.
*˝˝
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive of the parent select element.
*
* 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 `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 currently
* be bound to string values only.
*
* @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`
* * 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.
*
* @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="">-- chose 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 });
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000077770
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/,
nullModelCtrl = {$setViewValue: noop};
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) {
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) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(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.bind('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(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.bind('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.find('option'), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + optionsExp + "'.");
}
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]),
// 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.bind('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index, groupIndex, length, groupLength;
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;
locals[valueName] = collection[key];
value.push(valueFn(scope, locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} 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() {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element,
label;
if (multiple) {
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++) {
locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
optionGroupName = groupByFn(scope, locals) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = selectedSet.remove(valueFn(scope, locals)) != undefined;
} 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
label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
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.bind('$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 || {};
/**
* 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() {
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 prefix = 'expect ' + this.future.name + ' ';
if (this.inverse) {
prefix += 'not ';
}
var self = this;
this.addFuture(prefix + name + ' ' + angular.toJson(expected),
function(done) {
var error;
self.actual = self.future.value;
if ((self.inverse && fn.call(self, expected)) ||
(!self.inverse && !fn.call(self, expected))) {
error = 'expected ' + angular.toJson(expected) +
' 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 continute 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 || '';
};
}
/**
* 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} type Optional event type.
* @param {Array.<string>=} keys Optional list of pressed keys
* (valid values: 'alt', 'meta', 'shift', 'ctrl')
*/
function browserTrigger(element, type, keys) {
if (element && !element.nodeName) element = element[0];
if (!element) return;
if (!type) {
type = {
'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'
}[lowercase(element.type)] || 'click';
}
if (lowercase(nodeName_(element)) == 'option') {
element.parentNode.value = element.value;
element = element.parentNode;
type = 'change';
}
keys = keys || [];
function pressed(key) {
return indexOf(keys, key) !== -1;
}
if (msie < 9) {
switch(element.type) {
case 'radio':
case 'checkbox':
element.checked = !element.checked;
break;
}
// 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' + type);
if (lowercase(element.type) == 'submit') {
while(element) {
if (lowercase(element.nodeName) == 'form') {
element.fireEvent('onsubmit');
break;
}
element = element.parentNode;
}
}
return ret;
} else {
var evnt = document.createEvent('MouseEvents'),
originalPreventDefault = evnt.preventDefault,
iframe = _jQuery('#application iframe')[0],
appWindow = iframe ? iframe.contentWindow : window,
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);
};
evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'),
pressed('shift'), pressed('meta'), 0, element);
element.dispatchEvent(evnt);
finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault);
delete angular['ff-684208-preventDefault'];
return finalProcessDefault;
}
}
/**
* 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)/.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;
};
/**
* 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 = this.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);
this.executeAction(loadFn);
} else {
frame.remove();
this.context.find('#test-frames').append('<iframe>');
frame = this.getFrame_();
frame.load(function() {
frame.unbind();
try {
self.executeAction(loadFn);
} catch (e) {
errorFn(e);
}
}).attr('src', url);
}
this.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()} vody 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 of the future action
* @param {function()} future callback(error, result)
* @param {function()} 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);
var 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} 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} step 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} step 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 finshes. 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:contains("' + value + '")');
if (option.length) {
select.val(option.val());
}
}
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).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.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
: futureName = "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.element(document).find('head').append('<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 display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>');
angular.element(document).find('head').append('<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>'); |
src/svg-icons/action/home.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHome = (props) => (
<SvgIcon {...props}>
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
</SvgIcon>
);
ActionHome = pure(ActionHome);
ActionHome.displayName = 'ActionHome';
ActionHome.muiName = 'SvgIcon';
export default ActionHome;
|
ajax/libs/react-native-web/0.0.0-ec235e734/exports/createElement/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import AccessibilityUtil from '../../modules/AccessibilityUtil';
import createDOMProps from '../../modules/createDOMProps';
import React from 'react';
var createElement = function createElement(component, props) {
// Use equivalent platform elements where possible.
var accessibilityComponent;
if (component && component.constructor === String) {
accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props);
}
var Component = accessibilityComponent || component;
var domProps = createDOMProps(Component, props);
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
return /*#__PURE__*/React.createElement.apply(React, [Component, domProps].concat(children));
};
export default createElement; |
app/components/channel-selector.js | ForbesLindesay/chat-example | 'use strict';
import React from 'react';
import connect from '../../bicycle/connect';
import { Link } from 'react-router';
@connect(props => ({
channels: {}
}))
export default class ChannelSelector {
render() {
if (this.props.channels) {
return (
<ul>
{
this.props.channels.map(channel => (
<li key={channel.id}>
<Link to={"/" + channel.id}>{channel.name}</Link>
</li>
))
}
</ul>
);
} else {
return (<div>Loading Channels...</div>);
}
}
};
|
app/containers/AboutContainer.js | orballo/game-of-life | 'use strict'
import React from 'react'
import About from '../components/About.js'
const AboutContainer = React.createClass({
getInitialState() {
return {
isAboutHidden: true
}
},
componentDidMount() {
window.addEventListener('keydown', (e) => {
if (e.keyCode === 73) { // I key binding
if (!e.ctrlKey) this._showAbout()
} else if (e.keyCode === 27) { // Escape key binding
if (!this.state.isAboutHidden) this._showAbout()
}
})
},
_showAbout () {
let isHidden = this.state.isAboutHidden
this.setState({
isAboutHidden: !isHidden
})
},
render () {
return (
<About
isHidden={this.state.isAboutHidden}
showAbout={this._showAbout} />
)
}
})
export default AboutContainer
|
docs/src/App.js | gocreating/redux-draft | import React from 'react';
import {
BrowserRouter as Router,
Route,
Switch,
} from 'react-router-dom';
import './App.css';
let App = () => (
<Router basename="/redux-draft">
<Switch>
<Route
exact
path="/"
component={require('./pages/HomePage').default}
/>
<Route
exact
path="/examples/raw-editor"
component={require('./pages/examples/RawEditorPage').default}
/>
<Route
exact
path="/examples/blank-editor"
component={require('./pages/examples/BlankEditorPage').default}
/>
<Route
exact
path="/examples/bs-editor"
component={require('./pages/examples/BsEditorPage').default}
/>
</Switch>
</Router>
);
export default App;
|
ajax/libs/react-redux/0.5.0/react-redux.js | Teino1978-Corp/Teino1978-Corp-cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("redux"));
else if(typeof define === 'function' && define.amd)
define(["react", "redux"], factory);
else if(typeof exports === 'object')
exports["ReactRedux"] = factory(require("react"), require("redux"));
else
root["ReactRedux"] = factory(root["React"], root["Redux"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_10__, __WEBPACK_EXTERNAL_MODULE_11__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(10);
var _react2 = _interopRequireDefault(_react);
var _componentsCreateAll = __webpack_require__(2);
var _componentsCreateAll2 = _interopRequireDefault(_componentsCreateAll);
var _createAll = _componentsCreateAll2['default'](_react2['default']);
var Provider = _createAll.Provider;
var connect = _createAll.connect;
exports.Provider = Provider;
exports.connect = connect;
/***/ },
/* 1 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = createStoreShape;
function createStoreShape(PropTypes) {
return PropTypes.shape({
subscribe: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired
});
}
module.exports = exports["default"];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = createAll;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createProvider = __webpack_require__(4);
var _createProvider2 = _interopRequireDefault(_createProvider);
var _createConnect = __webpack_require__(3);
var _createConnect2 = _interopRequireDefault(_createConnect);
function createAll(React) {
var Provider = _createProvider2['default'](React);
var connect = _createConnect2['default'](React);
return { Provider: Provider, connect: connect };
}
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _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; };
exports['default'] = createConnect;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
var _utilsCreateStoreShape = __webpack_require__(1);
var _utilsCreateStoreShape2 = _interopRequireDefault(_utilsCreateStoreShape);
var _utilsShallowEqualScalar = __webpack_require__(7);
var _utilsShallowEqualScalar2 = _interopRequireDefault(_utilsShallowEqualScalar);
var _utilsShallowEqual = __webpack_require__(6);
var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual);
var _utilsIsPlainObject = __webpack_require__(5);
var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);
var _utilsWrapActionCreators = __webpack_require__(8);
var _utilsWrapActionCreators2 = _interopRequireDefault(_utilsWrapActionCreators);
var _invariant = __webpack_require__(9);
var _invariant2 = _interopRequireDefault(_invariant);
var defaultMapState = function defaultMapState() {
return {};
};
var defaultMapDispatch = function defaultMapDispatch(dispatch) {
return { dispatch: dispatch };
};
var defaultMergeProps = function defaultMergeProps(stateSlice, actionsCreators, props) {
return _extends({}, props, stateSlice, actionsCreators);
};
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
function createConnect(React) {
var Component = React.Component;
var PropTypes = React.PropTypes;
var storeShape = _utilsCreateStoreShape2['default'](PropTypes);
return function connect() {
var _mapState = arguments.length <= 0 || arguments[0] === undefined ? defaultMapState : arguments[0];
var mapDispatchOrActionCreators = arguments.length <= 1 || arguments[1] === undefined ? defaultMapDispatch : arguments[1];
var mergeProps = arguments.length <= 2 || arguments[2] === undefined ? defaultMergeProps : arguments[2];
var shouldSubscribe = _mapState !== defaultMapState;
var _mapDispatch = _utilsIsPlainObject2['default'](mapDispatchOrActionCreators) ? _utilsWrapActionCreators2['default'](mapDispatchOrActionCreators) : mapDispatchOrActionCreators;
return function (DecoratedComponent) {
return (function (_Component) {
_inherits(ConnectDecorator, _Component);
ConnectDecorator.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
return this.subscribed && !this.isSliceEqual(this.state.slice, nextState.slice) || !_utilsShallowEqualScalar2['default'](this.props, nextProps);
};
ConnectDecorator.prototype.isSliceEqual = function isSliceEqual(slice, nextSlice) {
var isRefEqual = slice === nextSlice;
if (isRefEqual || typeof slice !== 'object' || typeof nextSlice !== 'object') {
return isRefEqual;
}
return _utilsShallowEqual2['default'](slice, nextSlice);
};
_createClass(ConnectDecorator, null, [{
key: 'displayName',
value: 'Connect(' + getDisplayName(DecoratedComponent) + ')',
enumerable: true
}, {
key: 'DecoratedComponent',
value: DecoratedComponent,
enumerable: true
}, {
key: 'contextTypes',
value: {
store: storeShape.isRequired
},
enumerable: true
}]);
function ConnectDecorator(props, context) {
_classCallCheck(this, ConnectDecorator);
_Component.call(this, props, context);
this.setUnderlyingRef = this.setUnderlyingRef.bind(this);
this.state = _extends({}, this.mapState(props, context), this.mapDispatch(context));
}
ConnectDecorator.prototype.componentDidMount = function componentDidMount() {
if (shouldSubscribe) {
this.subscribed = true;
this.unsubscribe = this.context.store.subscribe(this.handleChange.bind(this));
}
};
ConnectDecorator.prototype.componentWillUnmount = function componentWillUnmount() {
if (shouldSubscribe) {
this.unsubscribe();
}
};
ConnectDecorator.prototype.handleChange = function handleChange() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var nextState = this.mapState(props, this.context);
if (!this.isSliceEqual(this.state.slice, nextState.slice)) {
this.setState(nextState);
}
};
ConnectDecorator.prototype.mapState = function mapState() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var context = arguments.length <= 1 || arguments[1] === undefined ? this.context : arguments[1];
var state = context.store.getState();
var slice = _mapState(state);
_invariant2['default'](_utilsIsPlainObject2['default'](slice), '`mapState` must return an object. Instead received %s.', slice);
return { slice: slice };
};
ConnectDecorator.prototype.mapDispatch = function mapDispatch() {
var context = arguments.length <= 0 || arguments[0] === undefined ? this.context : arguments[0];
var dispatch = context.store.dispatch;
var actionCreators = _mapDispatch(dispatch);
_invariant2['default'](_utilsIsPlainObject2['default'](actionCreators), '`mapDispatch` must return an object. Instead received %s.', actionCreators);
return { actionCreators: actionCreators };
};
ConnectDecorator.prototype.merge = function merge() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var state = arguments.length <= 1 || arguments[1] === undefined ? this.state : arguments[1];
var slice = state.slice;
var actionCreators = state.actionCreators;
var merged = mergeProps(slice, actionCreators, props);
_invariant2['default'](_utilsIsPlainObject2['default'](merged), '`mergeProps` must return an object. Instead received %s.', merged);
return merged;
};
ConnectDecorator.prototype.getUnderlyingRef = function getUnderlyingRef() {
return this.underlyingRef;
};
ConnectDecorator.prototype.setUnderlyingRef = function setUnderlyingRef(instance) {
this.underlyingRef = instance;
};
ConnectDecorator.prototype.render = function render() {
return React.createElement(DecoratedComponent, _extends({ ref: this.setUnderlyingRef
}, this.merge()));
};
return ConnectDecorator;
})(Component);
};
};
}
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports['default'] = createProvider;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
var _utilsCreateStoreShape = __webpack_require__(1);
var _utilsCreateStoreShape2 = _interopRequireDefault(_utilsCreateStoreShape);
function createProvider(React) {
var Component = React.Component;
var PropTypes = React.PropTypes;
var storeShape = _utilsCreateStoreShape2['default'](PropTypes);
return (function (_Component) {
_inherits(Provider, _Component);
Provider.prototype.getChildContext = function getChildContext() {
return { store: this.state.store };
};
_createClass(Provider, null, [{
key: 'childContextTypes',
value: {
store: storeShape.isRequired
},
enumerable: true
}, {
key: 'propTypes',
value: {
children: PropTypes.func.isRequired
},
enumerable: true
}]);
function Provider(props, context) {
_classCallCheck(this, Provider);
_Component.call(this, props, context);
this.state = { store: props.store };
}
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var store = this.state.store;
var nextStore = nextProps.store;
if (store !== nextStore) {
var nextReducer = nextStore.getReducer();
store.replaceReducer(nextReducer);
}
};
Provider.prototype.render = function render() {
var children = this.props.children;
return children();
};
return Provider;
})(Component);
}
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = isPlainObject;
var fnToString = function fnToString(fn) {
return Function.prototype.toString.call(fn);
};
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype;
if (proto === null) {
return true;
}
var constructor = proto.constructor;
return typeof constructor === 'function' && constructor instanceof constructor && fnToString(constructor) === fnToString(Object);
}
module.exports = exports['default'];
/***/ },
/* 6 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = shallowEqual;
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = exports["default"];
/***/ },
/* 7 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = shallowEqualScalar;
function shallowEqualScalar(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i])) {
return false;
}
var valA = objA[keysA[i]];
var valB = objB[keysA[i]];
if (valA !== valB || typeof valA === 'object' || typeof valB === 'object') {
return false;
}
}
return true;
}
module.exports = exports['default'];
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = wrapActionCreators;
var _redux = __webpack_require__(11);
function wrapActionCreators(actionCreators) {
return function (dispatch) {
return _redux.bindActionCreators(actionCreators, dispatch);
};
}
module.exports = exports['default'];
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule 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 (true) {
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;
/***/ },
/* 10 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_10__;
/***/ },
/* 11 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_11__;
/***/ }
/******/ ])
});
; |
src/routes/NotFound.js | cherishstand/dva-quickstart | import React from 'react';
import { Link } from 'dva/router';
export default function NotFound() {
return (
<div id='page-404'>
<section>
<h1>404</h1>
<p>你要找的页面不存在 <Link to="/">返回首页</Link></p>
<style
dangerouslySetInnerHTML={{
__html: '#react-content { height: 100%; background-color: #fff }',
}}
/>
</section>
</div>
)
}
|
server/priv/js/app.js | bks7/mzbench | import 'babel-core/polyfill';
import React from 'react';
import MZBenchApp from './components/MZBenchApp.react';
import './utils/MZBenchRouter';
React.render(
<MZBenchApp />,
document.getElementById('mzbench-container')
);
|
src/components/MainNav.js | anjren/UncleChenWebsite | import React from 'react';
import { Link } from 'react-router-dom';
export class MainNav extends React.Component {
render() {
return (
<nav className="uc-main-nav">
<Link to="/"><img className="uc-main-nav__logo" type="image/png" src="/img/union_food_logo.png"/></Link>
<ul className="uc-main-nav__items">
<li><h6><Link to="/products">Products</Link></h6></li>
<li><h6><Link to="/recipes">Recipes</Link></h6></li>
<li><h6><Link to="/">About</Link></h6></li>
<li><h6><Link to="/news-and-events">News & Events</Link></h6></li>
</ul>
</nav>
)
}
}
export default MainNav;
|
ajax/libs/core-js/0.5.3/shim.js | tonytomov/cdnjs | /**
* Core.js 0.5.3
* https://github.com/zloirock/core-js
* License: http://rock.mit-license.org
* © 2015 Denis Pushkarev
*/
!function(global, framework, undefined){
'use strict';
/******************************************************************************
* Module : common *
******************************************************************************/
// Shortcuts for [[Class]] & property names
var 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'
// Aliases global objects and prototypes
, 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
, RangeError = global.RangeError
, setTimeout = global.setTimeout
, setImmediate = global.setImmediate
, clearImmediate = global.clearImmediate
, parseInt = global.parseInt
, isFinite = global.isFinite
, 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 = '.'
// Methods from https://github.com/DeveloperToolsWG/console-object/blob/master/api.md
, CONSOLE_METHODS = 'assert,clear,count,debug,dir,dirxml,error,exception,' +
'group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,' +
'markTimeline,profile,profileEnd,table,time,timeEnd,timeline,' +
'timelineEnd,timeStamp,trace,warn';
// http://jsperf.com/core-js-isobject
function isObject(it){
return it !== null && (typeof it == 'object' || typeof it == 'function');
}
function isFunction(it){
return typeof it == 'function';
}
// Native function?
var isNative = ctx(/./.test, /\[native code\]\s*\}\s*$/, 1);
// Object internal [[Class]] or toStringTag
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring
var 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 toString.call(it).slice(8, -1);
}
function classof(it){
var O, T;
return it == undefined ? it === undefined ? 'Undefined' : 'Null'
: typeof (T = (O = Object(it))[SYMBOL_TAG]) == 'string' ? T : cof(O);
}
// Function
var call = FunctionProto.call
, apply = FunctionProto.apply
, REFERENCE_GET;
// Partial apply
function part(/* ...args */){
var fn = assertFunction(this)
, length = arguments.length
, args = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((args[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, _length = arguments.length
, i = 0, j = 0, _args;
if(!holder && !_length)return invoke(fn, args, that);
_args = args.slice();
if(holder)for(;length > i; i++)if(_args[i] === _)_args[i] = arguments[j++];
while(_length > j)_args.push(arguments[j++]);
return invoke(fn, _args, that);
}
}
// Optional / simple context binding
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(/* ...args */){
return fn.apply(that, arguments);
}
}
// Fast apply
// http://jsperf.lnkit.com/fast-apply/5
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);
}
function construct(target, argumentsList /*, newTarget*/){
var proto = assertFunction(arguments.length < 3 ? target : arguments[2])[PROTOTYPE]
, instance = create(isObject(proto) ? proto : ObjectProto)
, result = apply.call(target, instance, argumentsList);
return isObject(result) ? result : instance;
}
// Object:
var create = Object.create
, getPrototypeOf = Object.getPrototypeOf
, setPrototypeOf = Object.setPrototypeOf
, defineProperty = Object.defineProperty
, defineProperties = Object.defineProperties
, getOwnDescriptor = Object.getOwnPropertyDescriptor
, getKeys = Object.keys
, getNames = Object.getOwnPropertyNames
, getSymbols = Object.getOwnPropertySymbols
, isFrozen = Object.isFrozen
, has = ctx(call, ObjectProto[HAS_OWN], 2)
// Dummy, fix for not array-like ES3 string in es5 module
, ES5Object = Object
, Dict;
function toObject(it){
return ES5Object(assertDefined(it));
}
function returnIt(it){
return it;
}
function returnThis(){
return this;
}
function get(object, key){
if(has(object, key))return object[key];
}
function ownKeys(it){
assertObject(it);
return getSymbols ? getNames(it).concat(getSymbols(it)) : getNames(it);
}
// 19.1.2.1 Object.assign(target, source, ...)
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 = toObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
}
// Array
// array('str1,str2,str3') => ['str1', 'str2', 'str3']
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];
/*
* 0 -> forEach
* 1 -> map
* 2 -> filter
* 3 -> some
* 4 -> every
* 5 -> find
* 6 -> findIndex
*/
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 = undefined */){
var O = Object(assertDefined(this))
, that = arguments[1]
, 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; // map
else if(res)switch(type){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(isEvery)return false; // every
}
}
return isFindIndex ? -1 : isSome || isEvery ? isEvery : result;
}
}
function createArrayContains(isContains){
return function(el /*, fromIndex = 0 */){
var O = toObject(this)
, length = toLength(O.length)
, index = toIndex(arguments[1], 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 generic(A, B){
// strange IE quirks mode bug -> use typeof vs isFunction
return typeof A == 'function' ? A : B;
}
// Math
var MAX_SAFE_INTEGER = 0x1fffffffffffff // pow(2, 53) - 1 == 9007199254740991
, pow = Math.pow
, abs = Math.abs
, 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);
}
// 20.1.2.4 Number.isNaN(number)
function sameNaN(number){
return number != number;
}
// 7.1.4 ToInteger
function toInteger(it){
return isNaN(it) ? 0 : trunc(it);
}
// 7.1.15 ToLength
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 lz(num){
return num > 9 ? num : '0' + num;
}
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 < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? toString ? s.charAt(i) : a
: toString ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
}
}
// Assertion & errors
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!");
}
// Property descriptors & Symbol
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);
}
// The engine works fine with descriptors? Thank's IE8 for his funny defineProperty.
var DESC = !!function(){
try {
return defineProperty({}, 'a', {get: function(){ return 2 }}).a == 2;
} 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_UNSCOPABLES = getWellKnownSymbol('unscopables')
, ArrayUnscopables = ArrayProto[SYMBOL_UNSCOPABLES] || {}
, SYMBOL_SPECIES = getWellKnownSymbol('species');
function setSpecies(C){
if(framework || !isNative(C))defineProperty(C, SYMBOL_SPECIES, {
configurable: true,
get: returnThis
});
}
// Iterators
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
// Safari define byggy iterators w/o `next`
, BUGGY_ITERATORS = 'keys' in ArrayProto && !('next' in [].keys());
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
setIterator(IteratorPrototype, returnThis);
function setIterator(O, value){
hidden(O, SYMBOL_ITERATOR, value);
// Add iterator for FF iterator protocol
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){
// Define iterator
setIterator(proto, iter);
if(iter !== value){
var iterProto = getPrototypeOf(iter.call(new Constructor));
// Set @@toStringTag to native iterators
setToStringTag(iterProto, NAME + ' Iterator', true);
// FF fix
has(proto, FF_ITERATOR) && setIterator(iterProto, returnThis);
}
}
// Plug for library
Iterators[NAME] = iter;
// FF & v8 fix
Iterators[NAME + ' Iterator'] = returnThis;
return iter;
}
function defineStdIterators(Base, NAME, Constructor, next, DEFAULT, IS_SET){
function createIter(kind){
return function(){
return new Constructor(this, kind);
}
}
createIterator(Constructor, NAME, next);
var entries = createIter(KEY+VALUE)
, values = createIter(VALUE);
if(DEFAULT == VALUE)values = defineIterator(Base, NAME, values, 'values');
else entries = defineIterator(Base, NAME, entries, 'entries');
if(DEFAULT){
$define(PROTO + FORCED * BUGGY_ITERATORS, NAME, {
entries: entries,
keys: IS_SET ? values : createIter(KEY),
values: values
});
}
}
function iterResult(done, value){
return {value: value, done: !!done};
}
function isIterable(it){
var O = Object(it)
, Symbol = global[SYMBOL]
, hasExt = (Symbol && Symbol[ITERATOR] || FF_ITERATOR) in O;
return hasExt || SYMBOL_ITERATOR in O || has(Iterators, classof(O));
}
function getIterator(it){
var Symbol = global[SYMBOL]
, ext = it[Symbol && Symbol[ITERATOR] || FF_ITERATOR]
, getIter = ext || it[SYMBOL_ITERATOR] || Iterators[classof(it)];
return assertObject(getIter.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;
}
// core
var NODE = cof(process) == PROCESS
, core = {}
, path = framework ? global : core
, old = global.core
, exportGlobal
// type bitmap
, 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){
// there is a similar native
own = !(type & FORCED) && target && key in target
&& (!isFunction(target[key]) || isNative(target[key]));
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
if(type & BIND && own)exp = ctx(out, global);
// wrap global constructors for prevent change them in library
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;
// export
if(exports[key] != out)hidden(exports, key, exp);
// extend global
if(framework && target && !own){
if(isGlobal)target[key] = out;
else delete target[key] && hidden(target, key, out);
}
}
}
// CommonJS export
if(typeof module != 'undefined' && module.exports)module.exports = core;
// RequireJS export
else if(isFunction(define) && define.amd)define(function(){return core});
// Export to global object
else exportGlobal = true;
if(exportGlobal || framework){
core.noConflict = function(){
global.core = old;
return core;
}
global.core = core;
}
/******************************************************************************
* Module : es5 *
******************************************************************************/
// ECMAScript 5 shim
!function(IS_ENUMERABLE, Empty, _classof, $PROTO){
if(!DESC){
getOwnDescriptor = function(O, P){
if(has(O, P))return descriptor(!ObjectProto[IS_ENUMERABLE].call(O, P), O[P]);
};
defineProperty = function(O, P, Attributes){
if('value' in Attributes)assertObject(O)[P] = Attributes.value;
return O;
};
defineProperties = function(O, Properties){
assertObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P, Attributes;
while(length > i){
P = keys[i++];
Attributes = Properties[P];
if('value' in Attributes)O[P] = Attributes.value;
}
return O;
};
}
$define(STATIC + FORCED * !DESC, OBJECT, {
// 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: getOwnDescriptor,
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
defineProperty: defineProperty,
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
defineProperties: defineProperties
});
// IE 8- don't enum bug keys
var keys1 = [CONSTRUCTOR, HAS_OWN, 'isPrototypeOf', IS_ENUMERABLE, TO_LOCALE, TO_STRING, 'valueOf']
// Additional keys for getOwnPropertyNames
, keys2 = keys1.concat('length', PROTOTYPE)
, keysLen1 = keys1.length;
// Create object with `null` prototype: use iframe Object with cleared prototype
function createDict(){
// Thrash, waste and sodomy: IE GC bug
var iframe = document[CREATE_ELEMENT]('iframe')
, i = keysLen1
, iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
iframe.src = 'javascript:';
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write('<script>document.F=Object</script>');
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][keys1[i]];
return createDict();
}
function createGetKeys(names, length, isNames){
return function(object){
var O = toObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != $PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(length > i)if(has(O, key = names[i++])){
~indexOf.call(result, key) || result.push(key);
}
return result;
}
}
function isPrimitive(it){ return !isObject(it) }
$define(STATIC, OBJECT, {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
getPrototypeOf: getPrototypeOf = getPrototypeOf || function(O){
O = Object(assertDefined(O));
if(has(O, $PROTO))return O[$PROTO];
if(isFunction(O[CONSTRUCTOR]) && O instanceof O[CONSTRUCTOR]){
return O[CONSTRUCTOR][PROTOTYPE];
} return O instanceof Object ? ObjectProto : null;
},
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
getOwnPropertyNames: getNames = getNames || createGetKeys(keys2, keys2.length, true),
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
create: create = create || function(O, /*?*/Properties){
var result
if(O !== null){
Empty[PROTOTYPE] = assertObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf shim
result[$PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : defineProperties(result, Properties);
},
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
keys: getKeys = getKeys || createGetKeys(keys1, keysLen1, false),
// 19.1.2.17 / 15.2.3.8 Object.seal(O)
seal: returnIt, // <- cap
// 19.1.2.5 / 15.2.3.9 Object.freeze(O)
freeze: returnIt, // <- cap
// 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O)
preventExtensions: returnIt, // <- cap
// 19.1.2.13 / 15.2.3.11 Object.isSealed(O)
isSealed: isPrimitive, // <- cap
// 19.1.2.12 / 15.2.3.12 Object.isFrozen(O)
isFrozen: isFrozen = isFrozen || isPrimitive, // <- cap
// 19.1.2.11 / 15.2.3.13 Object.isExtensible(O)
isExtensible: isObject // <- cap
});
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
$define(PROTO, FUNCTION, {
bind: function(that /*, args... */){
var fn = assertFunction(this)
, partArgs = slice.call(arguments, 1);
function bound(/* args... */){
var args = partArgs.concat(slice.call(arguments));
return this instanceof bound ? construct(fn, args) : invoke(fn, args, that);
}
return bound;
}
});
// Fix for not array-like ES3 string
function arrayMethodFix(fn){
return function(){
return fn.apply(ES5Object(this), arguments);
}
}
if(!(0 in Object(DOT) && DOT[0] == DOT)){
ES5Object = function(it){
return cof(it) == STRING ? it.split('') : Object(it);
}
slice = arrayMethodFix(slice);
}
$define(PROTO + FORCED * (ES5Object != Object), ARRAY, {
slice: slice,
join: arrayMethodFix(ArrayProto.join)
});
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
$define(STATIC, ARRAY, {
isArray: function(arg){
return cof(arg) == ARRAY
}
});
function createArrayReduce(isRight){
return function(callbackfn, memo){
assertFunction(callbackfn);
var O = toObject(this)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(2 > arguments.length)for(;;){
if(index in O){
memo = O[index];
index += i;
break;
}
index += i;
assert(isRight ? index >= 0 : length > index, REDUCE_ERROR);
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in O){
memo = callbackfn(memo, O[index], index, this);
}
return memo;
}
}
$define(PROTO, ARRAY, {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: forEach = forEach || createArrayMethod(0),
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: createArrayMethod(1),
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: createArrayMethod(2),
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: createArrayMethod(3),
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: createArrayMethod(4),
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: createArrayReduce(false),
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: createArrayReduce(true),
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: indexOf = indexOf || createArrayContains(false),
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function(el, fromIndex /* = @[*-1] */){
var O = toObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = min(index, toInteger(fromIndex));
if(index < 0)index = toLength(length + index);
for(;index >= 0; index--)if(index in O)if(O[index] === el)return index;
return -1;
}
});
// 21.1.3.25 / 15.5.4.20 String.prototype.trim()
$define(PROTO, STRING, {trim: createReplacer(/^\s*([\s\S]*\S)?\s*$/, '$1')});
// 20.3.3.1 / 15.9.4.4 Date.now()
$define(STATIC, DATE, {now: function(){
return +new Date;
}});
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
$define(PROTO, DATE, {toISOString: function(){
if(!isFinite(this))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}});
if(_classof(function(){return arguments}()) == OBJECT)classof = function(it){
var cof = _classof(it);
return cof == OBJECT && isFunction(it.callee) ? ARGUMENTS : cof;
}
}('propertyIsEnumerable', function(){}, classof, safeSymbol(PROTOTYPE));
/******************************************************************************
* Module : es6.symbol *
******************************************************************************/
// ECMAScript 6 symbols shim
!function(TAG, SymbolRegistry, AllSymbols, setter){
// 19.4.1.1 Symbol([description])
if(!isNative(Symbol)){
Symbol = function(description){
assert(!(this instanceof Symbol), SYMBOL + ' is not a ' + CONSTRUCTOR);
var tag = uid(description)
, sym = set(create(Symbol[PROTOTYPE]), TAG, tag);
AllSymbols[tag] = sym;
DESC && setter && defineProperty(ObjectProto, tag, {
configurable: true,
set: function(value){
hidden(this, tag, value);
}
});
return sym;
}
hidden(Symbol[PROTOTYPE], TO_STRING, function(){
return this[TAG];
});
}
$define(GLOBAL + WRAP, {Symbol: Symbol});
var symbolStatics = {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = Symbol(key);
},
// 19.4.2.4 Symbol.iterator
iterator: SYMBOL_ITERATOR,
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: part.call(keyOf, SymbolRegistry),
// 19.4.2.10 Symbol.species
species: SYMBOL_SPECIES,
// 19.4.2.13 Symbol.toStringTag
toStringTag: SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG, true),
// 19.4.2.14 Symbol.unscopables
unscopables: SYMBOL_UNSCOPABLES,
pure: safeSymbol,
set: set,
useSetter: function(){setter = true},
useSimple: function(){setter = false}
};
// 19.4.2.2 Symbol.hasInstance
// 19.4.2.3 Symbol.isConcatSpreadable
// 19.4.2.6 Symbol.match
// 19.4.2.8 Symbol.replace
// 19.4.2.9 Symbol.search
// 19.4.2.11 Symbol.split
// 19.4.2.12 Symbol.toPrimitive
forEach.call(array('hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive'),
function(it){
symbolStatics[it] = getWellKnownSymbol(it);
}
);
$define(STATIC, SYMBOL, symbolStatics);
setToStringTag(Symbol, SYMBOL);
$define(STATIC + FORCED * !isNative(Symbol), OBJECT, {
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: function(it){
var names = getNames(toObject(it)), result = [], key, i = 0;
while(names.length > i)has(AllSymbols, key = names[i++]) || result.push(key);
return result;
},
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: function(it){
var names = getNames(toObject(it)), result = [], key, i = 0;
while(names.length > i)has(AllSymbols, key = names[i++]) && result.push(AllSymbols[key]);
return result;
}
});
}(safeSymbol('tag'), {}, {}, true);
/******************************************************************************
* Module : es6.object *
******************************************************************************/
!function(tmp){
var objectStatic = {
// 19.1.3.1 Object.assign(target, source)
assign: assign,
// 19.1.3.10 Object.is(value1, value2)
is: function(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
}
};
// 19.1.3.19 Object.setPrototypeOf(O, proto)
// Works with __proto__ only. Old v8 can't works with null proto objects.
'__proto__' in ObjectProto && function(buggy, set){
try {
set = ctx(call, getOwnDescriptor(ObjectProto, '__proto__').set, 2);
set({}, ArrayProto);
} catch(e){ buggy = true }
objectStatic.setPrototypeOf = setPrototypeOf = 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);
if(framework){
// 19.1.3.6 Object.prototype.toString()
tmp[SYMBOL_TAG] = DOT;
if(cof(tmp) != DOT)hidden(ObjectProto, TO_STRING, function(){
return '[object ' + classof(this) + ']';
});
}
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, MATH, true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
}({});
/******************************************************************************
* Module : es6.object.statics-accept-primitives *
******************************************************************************/
!function(){
// Object static methods accept primitives
function wrapObjectMethod(key, MODE){
var fn = Object[key]
, exp = core[OBJECT][key]
, f = 0
, o = {};
if(!exp || isNative(exp)){
o[key] = MODE == 1 ? function(it){
return isObject(it) ? fn(it) : it;
} : MODE == 2 ? function(it){
return isObject(it) ? fn(it) : true;
} : MODE == 3 ? function(it){
return isObject(it) ? fn(it) : false;
} : MODE == 4 ? function(it, key){
return fn(toObject(it), key);
} : function(it){
return fn(toObject(it));
};
try { fn(DOT) }
catch(e){ f = 1 }
$define(STATIC + FORCED * f, OBJECT, o);
}
}
wrapObjectMethod('freeze', 1);
wrapObjectMethod('seal', 1);
wrapObjectMethod('preventExtensions', 1);
wrapObjectMethod('isFrozen', 2);
wrapObjectMethod('isSealed', 2);
wrapObjectMethod('isExtensible', 3);
wrapObjectMethod('getOwnPropertyDescriptor', 4);
wrapObjectMethod('getPrototypeOf');
wrapObjectMethod('keys');
wrapObjectMethod('getOwnPropertyNames');
}();
/******************************************************************************
* Module : es6.function *
******************************************************************************/
!function(NAME){
// 19.2.4.2 name
NAME in FunctionProto || defineProperty(FunctionProto, NAME, {
configurable: true,
get: function(){
var match = String(this).match(/^\s*function ([^ (]*)/)
, name = match ? match[1] : '';
has(this, NAME) || defineProperty(this, NAME, descriptor(5, name));
return name;
},
set: function(value){
has(this, NAME) || defineProperty(this, NAME, descriptor(0, value));
}
});
}('name');
/******************************************************************************
* Module : es6.number.constructor *
******************************************************************************/
Number('0o1') && Number('0b1') || function(_Number, NumberProto){
function toNumber(it){
if(isObject(it))it = toPrimitive(it);
if(typeof it == 'string' && it.length > 2 && it.charCodeAt(0) == 48){
var binary = false;
switch(it.charCodeAt(1)){
case 66 : case 98 : binary = true;
case 79 : case 111 : return parseInt(it.slice(2), binary ? 2 : 8);
}
} return +it;
}
function toPrimitive(it){
var fn, val;
if(isFunction(fn = it.valueOf) && !isObject(val = fn.call(it)))return val;
if(isFunction(fn = it[TO_STRING]) && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to number");
}
Number = function Number(it){
return this instanceof Number ? new _Number(toNumber(it)) : toNumber(it);
}
forEach.call(DESC ? getNames(_Number)
: array('MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY'), function(key){
key in Number || defineProperty(Number, key, getOwnDescriptor(_Number, key));
});
Number[PROTOTYPE] = NumberProto;
NumberProto[CONSTRUCTOR] = Number;
hidden(global, NUMBER, Number);
}(Number, Number[PROTOTYPE]);
/******************************************************************************
* Module : es6.number *
******************************************************************************/
!function(isInteger){
$define(STATIC, NUMBER, {
// 20.1.2.1 Number.EPSILON
EPSILON: pow(2, -52),
// 20.1.2.2 Number.isFinite(number)
isFinite: function(it){
return typeof it == 'number' && isFinite(it);
},
// 20.1.2.3 Number.isInteger(number)
isInteger: isInteger,
// 20.1.2.4 Number.isNaN(number)
isNaN: sameNaN,
// 20.1.2.5 Number.isSafeInteger(number)
isSafeInteger: function(number){
return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER;
},
// 20.1.2.6 Number.MAX_SAFE_INTEGER
MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
// 20.1.2.10 Number.MIN_SAFE_INTEGER
MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER,
// 20.1.2.12 Number.parseFloat(string)
parseFloat: parseFloat,
// 20.1.2.13 Number.parseInt(string, radix)
parseInt: parseInt
});
// 20.1.2.3 Number.isInteger(number)
}(Number.isInteger || function(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
});
/******************************************************************************
* Module : es6.math *
******************************************************************************/
// ECMAScript 6 shim
!function(){
// 20.2.2.28 Math.sign(x)
var E = Math.E
, exp = Math.exp
, log = Math.log
, sqrt = Math.sqrt
, sign = Math.sign || function(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
// 20.2.2.5 Math.asinh(x)
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1));
}
// 20.2.2.14 Math.expm1(x)
function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1;
}
$define(STATIC, MATH, {
// 20.2.2.3 Math.acosh(x)
acosh: function(x){
return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x;
},
// 20.2.2.5 Math.asinh(x)
asinh: asinh,
// 20.2.2.7 Math.atanh(x)
atanh: function(x){
return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2;
},
// 20.2.2.9 Math.cbrt(x)
cbrt: function(x){
return sign(x = +x) * pow(abs(x), 1 / 3);
},
// 20.2.2.11 Math.clz32(x)
clz32: function(x){
return (x >>>= 0) ? 32 - x[TO_STRING](2).length : 32;
},
// 20.2.2.12 Math.cosh(x)
cosh: function(x){
return (exp(x = +x) + exp(-x)) / 2;
},
// 20.2.2.14 Math.expm1(x)
expm1: expm1,
// 20.2.2.16 Math.fround(x)
// TODO: fallback for IE9-
fround: function(x){
return new Float32Array([x])[0];
},
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
hypot: function(value1, value2){
var sum = 0
, len1 = arguments.length
, len2 = len1
, args = Array(len1)
, larg = -Infinity
, arg;
while(len1--){
arg = args[len1] = +arguments[len1];
if(arg == Infinity || arg == -Infinity)return Infinity;
if(arg > larg)larg = arg;
}
larg = arg || 1;
while(len2--)sum += pow(args[len2] / larg, 2);
return larg * sqrt(sum);
},
// 20.2.2.18 Math.imul(x, y)
imul: function(x, y){
var UInt16 = 0xffff
, xn = +x
, yn = +y
, xl = UInt16 & xn
, yl = UInt16 & yn;
return 0 | xl * yl + ((UInt16 & xn >>> 16) * yl + xl * (UInt16 & yn >>> 16) << 16 >>> 0);
},
// 20.2.2.20 Math.log1p(x)
log1p: function(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x);
},
// 20.2.2.21 Math.log10(x)
log10: function(x){
return log(x) / Math.LN10;
},
// 20.2.2.22 Math.log2(x)
log2: function(x){
return log(x) / Math.LN2;
},
// 20.2.2.28 Math.sign(x)
sign: sign,
// 20.2.2.30 Math.sinh(x)
sinh: function(x){
return (abs(x = +x) < 1) ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2);
},
// 20.2.2.33 Math.tanh(x)
tanh: function(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
},
// 20.2.2.34 Math.trunc(x)
trunc: trunc
});
}();
/******************************************************************************
* Module : es6.string *
******************************************************************************/
!function(fromCharCode){
function assertNotRegExp(it){
if(cof(it) == REGEXP)throw TypeError();
}
$define(STATIC, STRING, {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function(x){
var res = []
, len = arguments.length
, i = 0
, code
while(len > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
},
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function(callSite){
var raw = toObject(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, {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: createPointAt(false),
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
endsWith: function(searchString /*, endPosition = @length */){
assertNotRegExp(searchString);
var that = String(assertDefined(this))
, endPosition = arguments[1]
, len = toLength(that.length)
, end = endPosition === undefined ? len : min(toLength(endPosition), len);
searchString += '';
return that.slice(end - searchString.length, end) === searchString;
},
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
includes: function(searchString /*, position = 0 */){
assertNotRegExp(searchString);
return !!~String(assertDefined(this)).indexOf(searchString, arguments[1]);
},
// 21.1.3.13 String.prototype.repeat(count)
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;
},
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
startsWith: function(searchString /*, position = 0 */){
assertNotRegExp(searchString);
var that = String(assertDefined(this))
, index = toLength(min(arguments[1], that.length));
searchString += '';
return that.slice(index, index + searchString.length) === searchString;
}
});
}(String.fromCharCode);
/******************************************************************************
* Module : es6.array *
******************************************************************************/
!function(){
$define(STATIC, ARRAY, {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = Object(assertDefined(arrayLike))
, mapfn = arguments[1]
, mapping = mapfn !== undefined
, f = mapping ? ctx(mapfn, arguments[2], 2) : undefined
, index = 0
, length, result, iter, step;
if(isIterable(O))for(iter = getIterator(O), result = new (generic(this, Array)); !(step = iter.next()).done; index++){
result[index] = mapping ? f(step.value, index) : step.value;
} else for(result = new (generic(this, Array))(length = toLength(O.length)); length > index; index++){
result[index] = mapping ? f(O[index], index) : O[index];
}
result.length = index;
return result;
},
// 22.1.2.3 Array.of( ...items)
of: function(/* ...args */){
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, {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
copyWithin: function(target /* = 0 */, start /* = 0, end = @length */){
var O = Object(assertDefined(this))
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments[2]
, 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;
},
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
fill: function(value /*, start = 0, end = @length */){
var O = Object(assertDefined(this))
, length = toLength(O.length)
, index = toIndex(arguments[1], length)
, end = arguments[2]
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
},
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
find: createArrayMethod(5),
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
findIndex: createArrayMethod(6)
});
if(framework){
// 22.1.3.31 Array.prototype[@@unscopables]
forEach.call(array('find,findIndex,fill,copyWithin,entries,keys,values'), function(it){
ArrayUnscopables[it] = true;
});
SYMBOL_UNSCOPABLES in ArrayProto || hidden(ArrayProto, SYMBOL_UNSCOPABLES, ArrayUnscopables);
}
setSpecies(Array);
}();
/******************************************************************************
* Module : es6.iterators *
******************************************************************************/
!function(at){
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
defineStdIterators(Array, ARRAY, function(iterated, kind){
set(this, ITER, {o: toObject(iterated), i: 0, k: kind});
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var iter = this[ITER]
, O = iter.o
, kind = iter.k
, index = iter.i++;
if(!O || index >= O.length){
iter.o = undefined;
return iterResult(1);
}
if(kind == KEY) return iterResult(0, index);
if(kind == VALUE)return iterResult(0, O[index]);
return iterResult(0, [index, O[index]]);
}, VALUE);
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators[ARGUMENTS] = Iterators[ARRAY];
// 21.1.3.27 String.prototype[@@iterator]()
defineStdIterators(String, STRING, function(iterated){
set(this, ITER, {o: String(iterated), i: 0});
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, 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);
});
}(createPointAt(true));
/******************************************************************************
* Module : es6.regexp *
******************************************************************************/
!function(RegExpProto, _RegExp){
function assertRegExpWrapper(fn){
return function(){
assert(cof(this) === REGEXP);
return fn(this);
}
}
// RegExp allows a regex with flags as the pattern
if(DESC && !function(){try{return RegExp(/a/g, 'i') == '/a/i'}catch(e){}}()){
RegExp = function RegExp(pattern, flags){
return new _RegExp(cof(pattern) == REGEXP && flags !== undefined
? pattern.source : pattern, flags);
}
forEach.call(getNames(_RegExp), function(key){
key in RegExp || defineProperty(RegExp, key, {
configurable: true,
get: function(){ return _RegExp[key] },
set: function(it){ _RegExp[key] = it }
});
});
RegExpProto[CONSTRUCTOR] = RegExp;
RegExp[PROTOTYPE] = RegExpProto;
hidden(global, REGEXP, RegExp);
}
// 21.2.5.3 get RegExp.prototype.flags()
if(/./g.flags != 'g')defineProperty(RegExpProto, 'flags', {
configurable: true,
get: assertRegExpWrapper(createReplacer(/^.*\/(\w*)$/, '$1', true))
});
// 21.2.5.12 get RegExp.prototype.sticky()
// 21.2.5.15 get RegExp.prototype.unicode()
forEach.call(array('sticky,unicode'), function(key){
key in /./ || defineProperty(RegExpProto, key, DESC ? {
configurable: true,
get: assertRegExpWrapper(function(){
return false;
})
} : descriptor(5, false));
});
setSpecies(RegExp);
}(RegExp[PROTOTYPE], RegExp);
/******************************************************************************
* Module : web.immediate *
******************************************************************************/
// setImmediate shim
// Node.js 0.9+ & IE10+ has setImmediate, else:
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);
}
// Node.js 0.8-
if(NODE){
defer = function(id){
nextTick(part.call(run, id));
}
// Modern browsers, skip implementation for WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is object
} else if(addEventListener && isFunction(postMessage) && !global.importScripts){
defer = function(id){
postMessage(id, '*');
}
addEventListener('message', listner, false);
// WebWorkers
} else if(isFunction(MessageChannel)){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listner;
defer = ctx(port.postMessage, port, 1);
// IE8-
} 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);
}
}
// Rest old browsers
} else {
defer = function(id){
setTimeout(run, 0, id);
}
}
}('onreadystatechange');
$define(GLOBAL + BIND, {
setImmediate: setImmediate,
clearImmediate: clearImmediate
});
/******************************************************************************
* Module : es6.promise *
******************************************************************************/
// ES6 promises shim
// Based on https://github.com/getify/native-promise-only/
!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; // unwrap
try {
if(then = isThenable(msg)){
wrapper = {def: def, done: false}; // wrap
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); // wrap
}
}
function reject(msg){
var def = this;
if(def.done)return;
def.done = true;
def = def.def || def; // unwrap
def.msg = msg;
def.state = 2;
notify(def);
}
function getConstructor(C){
var S = assertObject(C)[SYMBOL_SPECIES];
return S != undefined ? S : C;
}
// 25.4.3.1 Promise(executor)
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], {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function(onFulfilled, onRejected){
var S = assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];
var react = {
ok: isFunction(onFulfilled) ? onFulfilled : true,
fail: isFunction(onRejected) ? onRejected : false
} , P = react.P = new (S != undefined ? S : Promise)(function(resolve, reject){
react.res = assertFunction(resolve);
react.rej = assertFunction(reject);
}), def = this[DEF];
def.chain.push(react);
def.state && notify(def);
return P;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
assignHidden(Promise, {
// 25.4.4.1 Promise.all(iterable)
all: function(iterable){
var Promise = getConstructor(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);
});
},
// 25.4.4.4 Promise.race(iterable)
race: function(iterable){
var Promise = getConstructor(this);
return new Promise(function(resolve, reject){
forOf(iterable, false, function(promise){
Promise.resolve(promise).then(resolve, reject);
});
});
},
// 25.4.4.5 Promise.reject(r)
reject: function(r){
return new (getConstructor(this))(function(resolve, reject){
reject(r);
});
},
// 25.4.4.6 Promise.resolve(x)
resolve: function(x){
return isObject(x) && DEF in x && getPrototypeOf(x) === this[PROTOTYPE]
? x : new (getConstructor(this))(function(resolve, reject){
resolve(x);
});
}
});
}(nextTick || setImmediate, safeSymbol('def'));
setToStringTag(Promise, PROMISE);
setSpecies(Promise);
$define(GLOBAL + FORCED * !isNative(Promise), {Promise: Promise});
}(global[PROMISE]);
/******************************************************************************
* Module : es6.collections *
******************************************************************************/
// ECMAScript 6 collections shim
!function(){
var UID = safeSymbol('uid')
, O1 = safeSymbol('O1')
, WEAK = safeSymbol('weak')
, LEAK = safeSymbol('leak')
, LAST = safeSymbol('last')
, FIRST = safeSymbol('first')
, SIZE = DESC ? safeSymbol('size') : 'size'
, uid = 0
, tmp = {};
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];
if(framework)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, FOR_EACH) && has(proto, 'entries')))){
// create collection constructor
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, O1, 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;
// wrap to init collections from iterable
if(!NATIVE_ITERATORS || !C.length){
C = function(iterable){
assertInstance(this, C, NAME);
return initFromIterable(new Native, iterable);
}
C[PROTOTYPE] = proto;
if(framework)proto[CONSTRUCTOR] = C;
}
isWeak || inst[FOR_EACH](function(val, key){
buggyZero = 1 / key === -Infinity;
});
// fix converting -0 key to +0
if(buggyZero){
fixSVZ('delete');
fixSVZ('has');
isMap && fixSVZ('get');
}
// + fix .add & .set for chaining
if(buggyZero || chain !== inst)fixSVZ(ADDER, true);
}
setToStringTag(C, NAME);
setSpecies(C);
O[NAME] = C;
$define(GLOBAL + WRAP + FORCED * !isNative(C), O);
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
isWeak || defineStdIterators(C, NAME, function(iterated, kind){
set(this, ITER, {o: iterated, k: kind});
}, function(){
var iter = this[ITER]
, kind = iter.k
, entry = iter.l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){
// or finish the iteration
iter.o = undefined;
return iterResult(1);
}
// return step by kind
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, !isMap);
return C;
}
function fastKey(it, create){
// return primitive with prefix
if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it;
// can't set id to frozen object
if(isFrozen(it))return 'F';
if(!has(it, UID)){
// not necessary to add id
if(!create)return 'E';
// add missing object id
hidden(it, UID, ++uid);
// return object id with prefix
} return 'O' + it[UID];
}
function getEntry(that, key){
// fast case
var index = fastKey(key), entry;
if(index != 'F')return that[O1][index];
// frozen object case
for(entry = that[FIRST]; entry; entry = entry.n){
if(entry.k == key)return entry;
}
}
function def(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry)entry.v = value;
// create new entry
else {
that[LAST] = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that[LAST], // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that[FIRST])that[FIRST] = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index != 'F')that[O1][index] = entry;
} return that;
}
var collectionMethods = {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function(){
for(var that = this, data = that[O1], entry = that[FIRST]; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that[FIRST] = that[LAST] = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that[O1][entry.i];
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]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function(callbackfn /*, that = undefined */){
var f = ctx(callbackfn, arguments[1], 3)
, entry;
while(entry = entry ? entry.n : this[FIRST]){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function(key){
return !!getEntry(this, key);
}
}
// 23.1 Map Objects
Map = getCollection(Map, MAP, {
// 23.1.3.6 Map.prototype.get(key)
get: function(key){
var entry = getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function(key, value){
return def(this, key === 0 ? 0 : key, value);
}
}, collectionMethods, true);
// 23.2 Set Objects
Set = getCollection(Set, SET, {
// 23.2.3.1 Set.prototype.add(value)
add: function(value){
return def(this, value = value === 0 ? 0 : value, value);
}
}, collectionMethods);
function defWeak(that, key, value){
if(isFrozen(assertObject(key)))leakStore(that).set(key, value);
else {
has(key, WEAK) || hidden(key, WEAK, {});
key[WEAK][that[UID]] = value;
} return that;
}
function leakStore(that){
return that[LEAK] || hidden(that, LEAK, new Map)[LEAK];
}
var weakMethods = {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
if(isFrozen(key))return leakStore(this)['delete'](key);
return has(key, WEAK) && has(key[WEAK], this[UID]) && delete key[WEAK][this[UID]];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function(key){
if(!isObject(key))return false;
if(isFrozen(key))return leakStore(this).has(key);
return has(key, WEAK) && has(key[WEAK], this[UID]);
}
};
// 23.3 WeakMap Objects
WeakMap = getCollection(WeakMap, WEAKMAP, {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function(key){
if(isObject(key)){
if(isFrozen(key))return leakStore(this).get(key);
if(has(key, WEAK))return key[WEAK][this[UID]];
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function(key, value){
return defWeak(this, key, value);
}
}, weakMethods, true, true);
// IE11 WeakMap frozen keys fix
if(framework && new WeakMap().set(Object.freeze(tmp), 7).get(tmp) != 7){
forEach.call(array('delete,has,get,set'), function(key){
var method = WeakMap[PROTOTYPE][key];
WeakMap[PROTOTYPE][key] = function(a, b){
// store frozen objects on leaky map
if(isObject(a) && isFrozen(a)){
var result = leakStore(this)[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
};
});
}
// 23.4 WeakSet Objects
WeakSet = getCollection(WeakSet, WEAKSET, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function(value){
return defWeak(this, value, true);
}
}, weakMethods, false, true);
}();
/******************************************************************************
* Module : es6.reflect *
******************************************************************************/
!function(){
function Enumerate(iterated){
var keys = [], key;
for(key in iterated)keys.push(key);
set(this, ITER, {o: iterated, a: keys, i: 0});
}
createIterator(Enumerate, OBJECT, function(){
var iter = this[ITER]
, keys = iter.a
, key;
do {
if(iter.i >= keys.length)return iterResult(1);
} while(!((key = keys[iter.i++]) in iter.o));
return iterResult(0, key);
});
function wrap(fn){
return function(it){
assertObject(it);
try {
return fn.apply(undefined, arguments), true;
} catch(e){
return false;
}
}
}
function reflectGet(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc = getOwnDescriptor(assertObject(target), propertyKey), proto;
if(desc)return has(desc, 'value')
? desc.value
: desc.get === undefined
? undefined
: desc.get.call(receiver);
return isObject(proto = getPrototypeOf(target))
? reflectGet(proto, propertyKey, receiver)
: undefined;
}
function reflectSet(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = getOwnDescriptor(assertObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return reflectSet(proto, propertyKey, V, receiver);
}
ownDesc = descriptor(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = getOwnDescriptor(receiver, propertyKey) || descriptor(0);
existingDescriptor.value = V;
return defineProperty(receiver, propertyKey, existingDescriptor), true;
}
return ownDesc.set === undefined
? false
: (ownDesc.set.call(receiver, V), true);
}
var isExtensible = Object.isExtensible || returnIt;
var reflect = {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
apply: ctx(call, apply, 3),
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
construct: construct,
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
defineProperty: wrap(defineProperty),
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
deleteProperty: function(target, propertyKey){
var desc = getOwnDescriptor(assertObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
},
// 26.1.5 Reflect.enumerate(target)
enumerate: function(target){
return new Enumerate(assertObject(target));
},
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
get: reflectGet,
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
getOwnPropertyDescriptor: function(target, propertyKey){
return getOwnDescriptor(assertObject(target), propertyKey);
},
// 26.1.8 Reflect.getPrototypeOf(target)
getPrototypeOf: function(target){
return getPrototypeOf(assertObject(target));
},
// 26.1.9 Reflect.has(target, propertyKey)
has: function(target, propertyKey){
return propertyKey in target;
},
// 26.1.10 Reflect.isExtensible(target)
isExtensible: function(target){
return !!isExtensible(assertObject(target));
},
// 26.1.11 Reflect.ownKeys(target)
ownKeys: ownKeys,
// 26.1.12 Reflect.preventExtensions(target)
preventExtensions: wrap(Object.preventExtensions || returnIt),
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
set: reflectSet
}
// 26.1.14 Reflect.setPrototypeOf(target, proto)
if(setPrototypeOf)reflect.setPrototypeOf = function(target, proto){
return setPrototypeOf(assertObject(target), proto), true;
};
$define(GLOBAL, {Reflect: {}});
$define(STATIC, 'Reflect', reflect);
}();
/******************************************************************************
* Module : es7.proposals *
******************************************************************************/
!function(){
$define(PROTO, ARRAY, {
// https://github.com/domenic/Array.prototype.includes
includes: createArrayContains(true)
});
$define(PROTO, STRING, {
// https://github.com/mathiasbynens/String.prototype.at
at: createPointAt(true)
});
function createObjectToArray(isEntries){
return function(object){
var O = toObject(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, {
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-04/apr-9.md#51-objectentries-objectvalues
values: createObjectToArray(false),
entries: createObjectToArray(true)
});
$define(STATIC, REGEXP, {
// https://gist.github.com/kangax/9698100
escape: createReplacer(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true)
});
}();
/******************************************************************************
* Module : es7.abstract-refs *
******************************************************************************/
// https://github.com/zenparsing/es-abstract-refs
!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');
/******************************************************************************
* Module : js.array.statics *
******************************************************************************/
// JavaScript 1.6 / Strawman array statics shim
!function(arrayStatics){
function setArrayStatics(keys, length){
forEach.call(array(keys), function(key){
if(key in ArrayProto)arrayStatics[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');
$define(STATIC, ARRAY, arrayStatics);
}({});
/******************************************************************************
* Module : web.dom.itarable *
******************************************************************************/
!function(NodeList){
if(framework && NodeList && !(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){
hidden(NodeList[PROTOTYPE], SYMBOL_ITERATOR, Iterators[ARRAY]);
}
Iterators.NodeList = Iterators[ARRAY];
}(global.NodeList);
/******************************************************************************
* Module : web.timers *
******************************************************************************/
// ie9- setTimeout & setInterval additional parameters fix
!function(MSIE){
function wrap(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(part, slice.call(arguments, 2), isFunction(fn) ? fn : Function(fn)), time);
} : set;
}
$define(GLOBAL + BIND + FORCED * MSIE, {
setTimeout: setTimeout = wrap(setTimeout),
setInterval: wrap(setInterval)
});
// ie9- dirty check
}(!!navigator && /MSIE .\./.test(navigator.userAgent));
/******************************************************************************
* Module : web.console *
******************************************************************************/
!function(cap){
forEach.call(array(CONSOLE_METHODS), function(key){
cap[key] = function(){};
});
$define(GLOBAL, {console: {}});
$define(STATIC, 'console', cap);
}({});
}(typeof self != 'undefined' && self.Math === Math ? self : Function('return this')(), true); |
src/components/NotesResults.js | Grobim/pic-picker | import React from 'react';
import PropTypes from 'prop-types';
import './NotesResults.scss';
export default class NotesResults extends React.Component {
static propTypes = {
notes: PropTypes.array.isRequired
};
goToVotes () {
this.props.router.push('');
}
goToVotes = this.goToVotes.bind(this);
render () {
const notesItems = this.props.notes.map((note, id) => (
<tr key={note.id}>
<td>
{id + 1}
</td>
<td>
{note.id + 1}
</td>
<td>
{note.file}
</td>
<td>
{note.line}
</td>
<td>
{note.column}
</td>
<td>
<b>{note.note}</b>
</td>
</tr>
// return <li key={note.id}>{note.id + 1} (File {note.file}, Line {note.line}, Column {note.column}) - <b>{note.note}</b></li>
));
return (
<div>
<h4>Results!</h4>
<button className='btn' onClick={this.goToVotes}>
Go to votes
</button>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Id</th>
<th>File</th>
<th>Line</th>
<th>Column</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{notesItems}
</tbody>
</table>
</div>
);
}
}
|
js/login_patient.js | meghprkh/doctr | var React = require("react");
var Router = require('react-router');
var { Route, DefaultRoute, RouteHandler, Link, Navigation } = Router;
var TabBar = require("./tabbar.js");
var qwest=require('qwest');
qwest.base = baseURL;
var Form = React.createClass({
mixins: [Navigation],
contextTypes: {
router: React.PropTypes.func
},
componentWillMount: function() {
this.props.parent.setState({"tab":"login_patient"})
},
getInitialState: function(){
return {
failure:false
}
},
verify: function() {
qwest.post('login/user/',{
"email":document.getElementById("login-email").value,
"password":document.getElementById("login-password").value})
.then(function(response) {
console.log(response);
if(response.success) {
session.uid=response.uid;
session.token=response.token;
session.name=response.name;
session.doctor=false;
this.transitionTo("patient");
} else {
this.setState({failure:true})
}
}.bind(this));
},
render:function(){
return (
<div>
{this.state.failure?
(<div className="alert alert-danger" role="alert">Invalid Credentials</div>)
:""}
<div className="form-group">
<label>Email</label>
<input id="login-email" placeholder="Email"
className="form-control"/>
</div>
<div>
<div className="form-group">
<label>Password</label>
<input id="login-password" type="password" placeholder="Password" className="form-control"/>
</div>
<button className="btn btn-primary" onClick={this.verify}>Login</button>
</div>
</div>
)
}
});
module.exports=Form;
|
docs/src/components/app.js | Cadasta/django-skivvy | import React from 'react';
import Navigation from './navigation';
import Content from './content';
import RoundedToggle from './rounded_toggle';
import PureRenderMixin from 'react-pure-render/mixin';
import GithubSlugger from 'github-slugger';
import debounce from 'lodash.debounce';
import { brandNames, brandClasses } from '../custom';
import qs from 'querystring';
let slugger = new GithubSlugger();
let slug = title => { slugger.reset(); return slugger.slug(title); };
let languageOptions = [
{ title: 'cURL',
short: 'cURL',
value: 'curl' },
{ title: 'CLI',
short: 'cli',
value: 'cli' },
{ title: 'Python',
short: 'Python',
value: 'python' },
{ title: 'JavaScript',
short: 'JS',
value: 'javascript' },
{ title: 'Java',
short: 'Java',
value: 'java' },
{ title: 'Objective-C',
short: 'ObjC',
value: 'objc' },
{ title: 'Swift',
short: 'Swift',
value: 'swift' }
];
let defaultLanguage = languageOptions[0];
let debouncedReplaceState = debounce(hash => {
window.history.replaceState('', '', hash);
}, 100);
var App = React.createClass({
mixins: [PureRenderMixin],
propTypes: {
content: React.PropTypes.string.isRequired,
ast: React.PropTypes.object.isRequired
},
getInitialState() {
var active = 'Introduction';
if (process.browser) {
let hash = window.location.hash.split('#').pop();
// let languageFromURL = qs.parse(window.location.search.substring(1)).language;
// console.log(languageFromURL)
let languageFromURL = 'Python';
let language = languageOptions.find(option => option.title === languageFromURL) ||
defaultLanguage;
let mqls = [
{ name: 'widescreen', query: window.matchMedia('(min-width: 1200px)') },
{ name: 'desktop', query: window.matchMedia('(min-width: 961px)') },
{ name: 'tablet', query: window.matchMedia('(max-width: 960px)') },
{ name: 'mobile', query: window.matchMedia('(max-width: 640px)') }
];
mqls.forEach(q => q.query.addListener(this.mediaQueryChanged));
if (hash) {
let headingForHash = this.props.ast.children
.filter(child => child.type === 'heading')
.find(heading => heading.data.id === hash);
if (headingForHash) {
active = headingForHash.children[0].value;
}
}
return {
// media queryMatches
mqls: mqls,
// object of currently matched queries, like { desktop: true }
queryMatches: {},
language: language,
columnMode: 2,
activeSection: active,
// for the toggle-able navigation on mobile
showNav: false
};
} else {
return {
mqls: { },
queryMatches: {
desktop: true
},
language: defaultLanguage,
activeSection: '',
showNav: false
};
}
},
toggleNav() {
this.setState({ showNav: !this.state.showNav });
},
componentDidMount() {
this.mediaQueryChanged();
this.onScroll = debounce(this.onScrollImmediate, 100);
document.addEventListener('scroll', this.onScroll);
this.onScrollImmediate();
},
onScrollImmediate() {
var sections = document.querySelectorAll('div.section');
if (!sections.length) return;
for (var i = 0; i < sections.length; i++) {
var rect = sections[i].getBoundingClientRect();
if (rect.bottom > 0) {
this.setState({
activeSection: sections[i].getAttribute('data-title')
});
return;
}
}
},
mediaQueryChanged() {
this.setState({
queryMatches: this.state.mqls.reduce((memo, q) => {
memo[q.name] = q.query.matches;
return memo;
}, {})
});
},
componentWillUnmount() {
this.state.mqls.forEach(q => q.removeListener(this.mediaQueryChanged));
document.body.removeEventListener('scroll', this.onScroll);
},
onChangeLanguage(language) {
this.setState({ language }, () => {
if (window.history) {
window.history.pushState(null, null,
`?${qs.stringify({ language: language.title })}${window.location.hash}`);
}
});
},
componentDidUpdate(_, prevState) {
if (prevState.activeSection !== this.state.activeSection) {
// when the section changes, replace the hash
debouncedReplaceState(`#${slug(this.state.activeSection)}`);
} else if (prevState.language.title !== this.state.language.title ||
prevState.columnMode !== this.state.columnMode) {
// when the language changes, use the hash to set scroll
window.location.hash = window.location.hash;
}
},
navigationItemClicked(activeSection) {
setTimeout(() => {
this.setState({ activeSection });
}, 10);
if (!this.state.queryMatches.desktop) {
this.toggleNav();
}
},
toggleColumnMode() {
this.setState({
columnMode: this.state.columnMode === 1 ? 2 : 1
});
},
render() {
let ast = JSON.parse(JSON.stringify(this.props.ast));
let { activeSection, queryMatches, showNav, columnMode } = this.state;
let col1 = columnMode === 1 && queryMatches.desktop;
return (<div className='container unlimiter'>
{/* Content background */ }
{(!col1 && !queryMatches.mobile) && <div className={`fixed-top fixed-right ${queryMatches.desktop && 'space-left16'}`}>
<div className='fill-light col6 pin-right'></div>
</div>}
{/* Desktop nav */ }
{queryMatches.desktop && <div className='space-top5 scroll-styled overflow-auto pad1 width16 sidebar fixed-left fill-dark dark'>
<Navigation
navigationItemClicked={this.navigationItemClicked}
activeSection={activeSection}
ast={ast} />
</div>}
{/* Content */ }
<div className={`${queryMatches.desktop && 'space-left16'}`}>
<div className={col1 ? 'col8 margin1' : ''}>
<Content
leftClassname={col1 ? 'space-bottom4 pad2x prose clip' : 'space-bottom8 col6 pad2x prose clip'}
rightClassname={col1 ? 'space-bottom2 pad2 prose clip fill-light space-top5' : 'space-bottom4 col6 pad2 prose clip fill-light space-top5'}
ast={ast}
language={this.state.language}/>
</div>
</div>
{/* Header */ }
<div className={`fill-dark dark bottom-shadow fixed-top ${queryMatches.tablet ? 'pad1y pad2x col6' : 'pad0 width16'}`}>
<a href='/' className={`active space-top1 space-left1 pin-topleft icon round dark pad0 ${brandClasses}`}></a>
<div className={`strong small pad0
${queryMatches.mobile ? 'space-left3' : ''}
${queryMatches.tablet ? 'space-left2' : 'space-left4 line-height15' }`}>
{queryMatches.desktop ? brandNames.desktop :
queryMatches.mobile ? brandNames.mobile : brandNames.tablet}
</div>
{queryMatches.tablet && <div>
<button
onClick={this.toggleNav}
className={`short quiet pin-topright button rcon ${showNav ? 'caret-up' : 'caret-down'} space-right1 space-top1`}>
<span className='micro'>{activeSection}</span>
</button>
{showNav && <div
className='fixed-left keyline-top fill-dark pin-left col6 pad2 scroll-styled space-top5'>
<Navigation
navigationItemClicked={this.navigationItemClicked}
activeSection={activeSection}
ast={ast} />
</div>}
</div>}
</div>
</div>);
}
});
module.exports = App;
|
app/javascript/mastodon/features/notifications/components/notification.js | rutan/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import StatusContainer from '../../../containers/status_container';
import AccountContainer from '../../../containers/account_container';
import { injectIntl, FormattedMessage } from 'react-intl';
import Permalink from '../../../components/permalink';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { HotKeys } from 'react-hotkeys';
const notificationForScreenReader = (intl, message, timestamp) => {
const output = [message];
output.push(intl.formatDate(timestamp, { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' }));
return output.join(', ');
};
@injectIntl
export default class Notification extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
notification: ImmutablePropTypes.map.isRequired,
hidden: PropTypes.bool,
onMoveUp: PropTypes.func.isRequired,
onMoveDown: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleMoveUp = () => {
const { notification, onMoveUp } = this.props;
onMoveUp(notification.get('id'));
}
handleMoveDown = () => {
const { notification, onMoveDown } = this.props;
onMoveDown(notification.get('id'));
}
handleOpen = () => {
const { notification } = this.props;
if (notification.get('status')) {
this.context.router.history.push(`/statuses/${notification.get('status')}`);
} else {
this.handleOpenProfile();
}
}
handleOpenProfile = () => {
const { notification } = this.props;
this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`);
}
handleMention = e => {
e.preventDefault();
const { notification, onMention } = this.props;
onMention(notification.get('account'), this.context.router.history);
}
getHandlers () {
return {
moveUp: this.handleMoveUp,
moveDown: this.handleMoveDown,
open: this.handleOpen,
openProfile: this.handleOpenProfile,
mention: this.handleMention,
reply: this.handleMention,
};
}
renderFollow (notification, account, link) {
const { intl } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-follow focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.follow', defaultMessage: '{name} followed you' }, { name: account.get('acct') }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-user-plus' />
</div>
<FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} />
</div>
<AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
renderMention (notification) {
return (
<StatusContainer
id={notification.get('status')}
withDismiss
hidden={this.props.hidden}
onMoveDown={this.handleMoveDown}
onMoveUp={this.handleMoveUp}
contextType='notifications'
/>
);
}
renderFavourite (notification, link) {
const { intl } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-favourite focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.favourite', defaultMessage: '{name} favourited your status' }, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-star star-icon' />
</div>
<FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} />
</div>
</HotKeys>
);
}
renderReblog (notification, link) {
const { intl } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-reblog focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.reblog', defaultMessage: '{name} boosted your status' }, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-retweet' />
</div>
<FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
render () {
const { notification } = this.props;
const account = notification.get('account');
const displayNameHtml = { __html: account.get('display_name_html') };
const link = <bdi><Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} /></bdi>;
switch(notification.get('type')) {
case 'follow':
return this.renderFollow(notification, account, link);
case 'mention':
return this.renderMention(notification);
case 'favourite':
return this.renderFavourite(notification, link);
case 'reblog':
return this.renderReblog(notification, link);
}
return null;
}
}
|
packages/reactor-kitchensink/src/examples/Charts/Column/BasicColumn/BasicColumn.js | sencha/extjs-reactor | import React, { Component } from 'react';
import { Container } from '@extjs/ext-react';
import { Cartesian } from '@extjs/ext-react-charts';
import ChartToolbar from '../../ChartToolbar';
import createData from './createData';
Ext.require([
'Ext.chart.series.Bar',
'Ext.chart.axis.Numeric',
'Ext.chart.axis.Category'
]);
export default class BasicColumnChartExample extends Component {
constructor() {
super();
this.refresh();
}
store = Ext.create('Ext.data.Store', {
fields: [
'month',
'high',
'low',
{
name: 'highF',
calculate: function (data) {
return data.high * 1.8 + 32;
}
},
{
name: 'lowF',
calculate: function (data) {
return data.low * 1.8 + 32;
}
}
]
});
state = {
theme: 'default'
};
refresh = () => {
this.store.loadData(createData());
}
changeTheme = theme => this.setState({ theme })
render() {
const { theme } = this.state;
return (
<Container layout="fit" padding={8}>
<ChartToolbar
onRefreshClick={this.refresh}
onThemeChange={this.changeTheme}
theme={theme}
/>
<Cartesian
shadow
insetPadding="20 10"
store={this.store}
theme={theme}
axes={[{
type: 'numeric',
position: 'left',
minimum: 30,
title: 'Temperature in °F'
}, {
type: 'category',
position: 'bottom'
}]}
series={[{
type: 'bar',
xField: 'month',
yField: 'highF'
}]}
/>
</Container>
)
}
} |
src/parser/shaman/restoration/modules/talents/HighTide.js | sMteX/WoWAnalyzer | import React from 'react';
import HIT_TYPES from 'game/HIT_TYPES';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
import { formatPercentage } from 'common/format';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveHealing from 'parser/core/calculateEffectiveHealing';
import StatTracker from 'parser/shared/modules/StatTracker';
import CritEffectBonus from 'parser/shared/modules/helpers/CritEffectBonus';
import StatisticListBoxItem from 'interface/others/StatisticListBoxItem';
const HEAL_WINDOW_MS = 150;
const bounceReduction = 0.7;
/**
* High Tide:
* Every 40000 mana you spend brings a High Tide, making your next 2 Chain Heals heal for an additional 20% and not reduce with each jump.
*/
class HighTide extends Analyzer {
static dependencies = {
statTracker: StatTracker,
critEffectBonus: CritEffectBonus,
};
healing = 0;
chainHealTimestamp = 0;
buffer = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.HIGH_TIDE_TALENT.id);
this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.CHAIN_HEAL), this.chainHeal);
this.addEventListener(Events.fightend, this.onFightEnd);
}
chainHeal(event) {
const hasHighTide = this.selectedCombatant.hasBuff(SPELLS.HIGH_TIDE_BUFF.id);
if (!hasHighTide) {
return;
}
// Detects new chain heal casts, can't use the cast event for this as its often somewhere in between its healing events
if (!this.chainHealTimestamp || event.timestamp - this.chainHealTimestamp > HEAL_WINDOW_MS) {
this.processBuffer();
this.chainHealTimestamp = event.timestamp;
}
/**
* Due to how Chain Heal interacts with the combatlog, we have to take a lot of extra steps here.
* Issues:
* 1. The healing events are backwards [4,3,2,1]
* 2. If the Shaman heals himself, his healing event is always first [3,4,2,1] (3 = Shaman)
* 3. If 2. happens, the heal on the shaman is also happening before the cast event, which the lines above already deal with.
*
* Calculating out High Tide requires us to know the exact jump order, as High Tide affects each jump differently.
* https://ancestralguidance.com/hidden-spell-mechanics/
* The solution is to reorder the events into the correct hit order, which could be done since each consecutive heal is weaker
* than the one beforehand (by 30%), except, you have the Shaman mastery which will result in random healing numbers
* as each hit has a different mastery effectiveness - the higher the Shamans mastery, the more rapidly different the numbers end up.
* With traits like https://www.wowhead.com/spell=277942/ancestral-resonance existing, shamans mastery can randomly double or triple mid combat.
*
* So we take 1 cast of chain heal at a time (4 hits maximum), calculate out crits and the mastery bonus, reorder them according to the new values
* (High healing to Low healing or [4,3,2,1] to [1,2,3,4]) and get the High Tide contribution by comparing the original heal values against
* what a non-High Tide Chain Heal would have done each bounce.
*
* Things that are able to break the sorting: Deluge (Pls don't take it) as its undetectable, random player-based heal increases
* (possibly encounter mechanics) if not accounted for.
*/
let heal = event.amount + (event.absorbed || 0) + (event.overheal || 0);
if (event.hitType === HIT_TYPES.CRIT) {
const critMult = this.critEffectBonus.getBonus(event);
heal /= critMult;
}
const currentMastery = this.statTracker.currentMasteryPercentage;
const masteryEffectiveness = Math.max(0, 1 - (event.hitPoints - event.amount) / event.maxHitPoints);
const baseHealingDone = heal / (1 + currentMastery * masteryEffectiveness);
this.buffer.push({
baseHealingDone: baseHealingDone,
...event,
});
}
processBuffer() {
this.buffer.sort((a, b) => parseFloat(b.baseHealingDone) - parseFloat(a.baseHealingDone));
for (const [index, event] of Object.entries(this.buffer)) {
// 20%, 71%, 145%, 250% increase per hit over not having High Tide
const FACTOR_CONTRIBUTED_BY_HT_HIT = (SPELLS.HIGH_TIDE_BUFF.coefficient) / (SPELLS.CHAIN_HEAL.coefficient * bounceReduction ** index) - 1;
this.healing += calculateEffectiveHealing(event, FACTOR_CONTRIBUTED_BY_HT_HIT);
}
this.buffer = [];
}
onFightEnd() {
this.processBuffer();
}
subStatistic() {
return (
<StatisticListBoxItem
title={<SpellLink id={SPELLS.HIGH_TIDE_TALENT.id} />}
value={`${formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.healing))} %`}
/>
);
}
}
export default HighTide;
|
example/material-ui/src/theme.js | supostat/react-confirm | import React from 'react';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
const Theme = (props) => (
<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
{ props.children }
</MuiThemeProvider>
);
export default Theme; |
frontend/src/components/h5/Button.js | sunlong/h5 | /**
* Created by sunlong on 2017/3/20.
*/
import React from 'react';
import Rnd from '../common/rnd/ReactRnd';
import store from '../../store';
import { changeFocus } from '../../actions/h5Actions';
function Input({ value, focusId }) {
const onClicked = () => {
store.dispatch(changeFocus({ id: value.id, type: 'button' }));
};
return (
<Rnd onClick={onClicked} className={focusId === value.id ? 'focused' : ''} style={value.style}>
<button type={value.type}>{value.text}</button>
</Rnd>
);
}
export default Input;
|
files/jquery.handsontable/0.10.3/jquery.handsontable.full.js | yaplas/jsdelivr | /**
* Handsontable 0.10.3
* Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs
*
* Copyright 2012, Marcin Warpechowski
* Licensed under the MIT license.
* http://handsontable.com/
*
* Date: Mon Feb 10 2014 14:15:11 GMT+0100 (CET)
*/
/*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */
var Handsontable = { //class namespace
extension: {}, //extenstion namespace
helper: {} //helper namespace
};
(function ($, window, Handsontable) {
"use strict";
//http://stackoverflow.com/questions/3629183/why-doesnt-indexof-work-on-an-array-ie8
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
/**
* Array.filter() shim by Trevor Menagh (https://github.com/trevmex) with some modifications
*/
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun, thisp) {
"use strict";
if (typeof this === "undefined" || this === null) {
throw new TypeError();
}
if (typeof fun !== "function") {
throw new TypeError();
}
thisp = thisp || this;
if (isNodeList(thisp)) {
thisp = convertNodeListToArray(thisp);
}
var len = thisp.length,
res = [],
i,
val;
for (i = 0; i < len; i += 1) {
if (thisp.hasOwnProperty(i)) {
val = thisp[i]; // in case fun mutates this
if (fun.call(thisp, val, i, thisp)) {
res.push(val);
}
}
}
return res;
function isNodeList(object) {
return /NodeList/i.test(object.item);
}
function convertNodeListToArray(nodeList) {
var array = [];
for (var i = 0, len = nodeList.length; i < len; i++){
array[i] = nodeList[i]
}
return array;
}
};
}
/*
* Copyright 2012 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
if (typeof WeakMap === 'undefined') {
(function() {
var defineProperty = Object.defineProperty;
try {
var properDefineProperty = true;
defineProperty(function(){}, 'foo', {});
} catch (e) {
properDefineProperty = false;
}
/*
IE8 does not support Date.now() but IE8 compatibility mode in IE9 and IE10 does.
M$ deserves a high five for this one :)
*/
var counter = +(new Date) % 1e9;
var WeakMap = function() {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
if(!properDefineProperty){
this._wmCache = [];
}
};
if(properDefineProperty){
WeakMap.prototype = {
set: function(key, value) {
var entry = key[this.name];
if (entry && entry[0] === key)
entry[1] = value;
else
defineProperty(key, this.name, {value: [key, value], writable: true});
},
get: function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ?
entry[1] : undefined;
},
'delete': function(key) {
this.set(key, undefined);
}
};
} else {
WeakMap.prototype = {
set: function(key, value) {
if(typeof key == 'undefined' || typeof value == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
this._wmCache[i].value = value;
return;
}
}
this._wmCache.push({key: key, value: value});
},
get: function(key) {
if(typeof key == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
return this._wmCache[i].value;
}
}
return;
},
'delete': function(key) {
if(typeof key == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
Array.prototype.slice.call(this._wmCache, i, 1);
}
}
}
};
}
window.WeakMap = WeakMap;
})();
}
Handsontable.activeGuid = null;
/**
* Handsontable constructor
* @param rootElement The jQuery element in which Handsontable DOM will be inserted
* @param userSettings
* @constructor
*/
Handsontable.Core = function (rootElement, userSettings) {
var priv
, datamap
, grid
, selection
, editorManager
, autofill
, instance = this
, GridSettings = function () {};
Handsontable.helper.extend(GridSettings.prototype, DefaultSettings.prototype); //create grid settings as a copy of default settings
Handsontable.helper.extend(GridSettings.prototype, userSettings); //overwrite defaults with user settings
Handsontable.helper.extend(GridSettings.prototype, expandType(userSettings));
this.rootElement = rootElement;
var $document = $(document.documentElement);
var $body = $(document.body);
this.guid = 'ht_' + Handsontable.helper.randomString(); //this is the namespace for global events
if (!this.rootElement[0].id) {
this.rootElement[0].id = this.guid; //if root element does not have an id, assign a random id
}
priv = {
cellSettings: [],
columnSettings: [],
columnsSettingConflicts: ['data', 'width'],
settings: new GridSettings(), // current settings instance
settingsFromDOM: {},
selStart: new Handsontable.SelectionPoint(),
selEnd: new Handsontable.SelectionPoint(),
isPopulated: null,
scrollable: null,
extensions: {},
firstRun: true
};
grid = {
/**
* Inserts or removes rows and columns
* @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col"
* @param {Number} index
* @param {Number} amount
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
*/
alter: function (action, index, amount, source, keepEmptyRows) {
var delta;
amount = amount || 1;
switch (action) {
case "insert_row":
delta = datamap.createRow(index, amount);
if (delta) {
if (priv.selStart.exists() && priv.selStart.row() >= index) {
priv.selStart.row(priv.selStart.row() + delta);
selection.transformEnd(delta, 0); //will call render() internally
}
else {
selection.refreshBorders(); //it will call render and prepare methods
}
}
break;
case "insert_col":
delta = datamap.createCol(index, amount);
if (delta) {
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
var spliceArray = [index, 0];
spliceArray.length += delta; //inserts empty (undefined) elements at the end of an array
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); //inserts empty (undefined) elements into the colHeader array
}
if (priv.selStart.exists() && priv.selStart.col() >= index) {
priv.selStart.col(priv.selStart.col() + delta);
selection.transformEnd(0, delta); //will call render() internally
}
else {
selection.refreshBorders(); //it will call render and prepare methods
}
}
break;
case "remove_row":
datamap.removeRow(index, amount);
priv.cellSettings.splice(index, amount);
grid.adjustRowsAndCols();
selection.refreshBorders(); //it will call render and prepare methods
break;
case "remove_col":
datamap.removeCol(index, amount);
for(var row = 0, len = datamap.getAll().length; row < len; row++){
if(row in priv.cellSettings){ //if row hasn't been rendered it wouldn't have cellSettings
priv.cellSettings[row].splice(index, amount);
}
}
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
if(typeof index == 'undefined'){
index = -1;
}
instance.getSettings().colHeaders.splice(index, amount);
}
priv.columnSettings.splice(index, amount);
grid.adjustRowsAndCols();
selection.refreshBorders(); //it will call render and prepare methods
break;
default:
throw new Error('There is no such action "' + action + '"');
break;
}
if (!keepEmptyRows) {
grid.adjustRowsAndCols(); //makes sure that we did not add rows that will be removed in next refresh
}
},
/**
* Makes sure there are empty rows at the bottom of the table
*/
adjustRowsAndCols: function () {
var r, rlen, emptyRows = instance.countEmptyRows(true), emptyCols;
//should I add empty rows to data source to meet minRows?
rlen = instance.countRows();
if (rlen < priv.settings.minRows) {
for (r = 0; r < priv.settings.minRows - rlen; r++) {
datamap.createRow(instance.countRows(), 1, true);
}
}
//should I add empty rows to meet minSpareRows?
if (emptyRows < priv.settings.minSpareRows) {
for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) {
datamap.createRow(instance.countRows(), 1, true);
}
}
//count currently empty cols
emptyCols = instance.countEmptyCols(true);
//should I add empty cols to meet minCols?
if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) {
for (; instance.countCols() < priv.settings.minCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, true);
}
}
//should I add empty cols to meet minSpareCols?
if (!priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) {
for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, true);
}
}
if (priv.settings.enterBeginsEditing) {
for (; (((priv.settings.minRows || priv.settings.minSpareRows) && instance.countRows() > priv.settings.minRows) && (priv.settings.minSpareRows && emptyRows > priv.settings.minSpareRows)); emptyRows--) {
datamap.removeRow();
}
}
if (priv.settings.enterBeginsEditing && !priv.settings.columns) {
for (; (((priv.settings.minCols || priv.settings.minSpareCols) && instance.countCols() > priv.settings.minCols) && (priv.settings.minSpareCols && emptyCols > priv.settings.minSpareCols)); emptyCols--) {
datamap.removeCol();
}
}
var rowCount = instance.countRows();
var colCount = instance.countCols();
if (rowCount === 0 || colCount === 0) {
selection.deselect();
}
if (priv.selStart.exists()) {
var selectionChanged;
var fromRow = priv.selStart.row();
var fromCol = priv.selStart.col();
var toRow = priv.selEnd.row();
var toCol = priv.selEnd.col();
//if selection is outside, move selection to last row
if (fromRow > rowCount - 1) {
fromRow = rowCount - 1;
selectionChanged = true;
if (toRow > fromRow) {
toRow = fromRow;
}
} else if (toRow > rowCount - 1) {
toRow = rowCount - 1;
selectionChanged = true;
if (fromRow > toRow) {
fromRow = toRow;
}
}
//if selection is outside, move selection to last row
if (fromCol > colCount - 1) {
fromCol = colCount - 1;
selectionChanged = true;
if (toCol > fromCol) {
toCol = fromCol;
}
} else if (toCol > colCount - 1) {
toCol = colCount - 1;
selectionChanged = true;
if (fromCol > toCol) {
fromCol = toCol;
}
}
if (selectionChanged) {
instance.selectCell(fromRow, fromCol, toRow, toCol);
}
}
},
/**
* Populate cells at position with 2d array
* @param {Object} start Start selection position
* @param {Array} input 2d array
* @param {Object} [end] End selection position (only for drag-down mode)
* @param {String} [source="populateFromArray"]
* @param {String} [method="overwrite"]
* @return {Object|undefined} ending td in pasted area (only if any cell was changed)
*/
populateFromArray: function (start, input, end, source, method) {
var r, rlen, c, clen, setData = [], current = {};
rlen = input.length;
if (rlen === 0) {
return false;
}
var repeatCol
, repeatRow
, cmax
, rmax;
// insert data with specified pasteMode method
switch (method) {
case 'shift_down' :
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
input = Handsontable.helper.translateRowsToColumns(input);
for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) {
if (c < clen) {
for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) {
input[c].push(input[c][r % rlen]);
}
input[c].unshift(start.col + c, start.row, 0);
instance.spliceCol.apply(instance, input[c]);
}
else {
input[c % clen][0] = start.col + c;
instance.spliceCol.apply(instance, input[c % clen]);
}
}
break;
case 'shift_right' :
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) {
if (r < rlen) {
for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) {
input[r].push(input[r][c % clen]);
}
input[r].unshift(start.row + r, start.col, 0);
instance.spliceRow.apply(instance, input[r]);
}
else {
input[r % rlen][0] = start.row + r;
instance.spliceRow.apply(instance, input[r % rlen]);
}
}
break;
case 'overwrite' :
default:
// overwrite and other not specified options
current.row = start.row;
current.col = start.col;
for (r = 0; r < rlen; r++) {
if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) {
break;
}
current.col = start.col;
clen = input[r] ? input[r].length : 0;
for (c = 0; c < clen; c++) {
if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) {
break;
}
if (!instance.getCellMeta(current.row, current.col).readOnly) {
setData.push([current.row, current.col, input[r][c]]);
}
current.col++;
if (end && c === clen - 1) {
c = -1;
}
}
current.row++;
if (end && r === rlen - 1) {
r = -1;
}
}
instance.setDataAtCell(setData, null, null, source || 'populateFromArray');
break;
}
},
/**
* Returns the top left (TL) and bottom right (BR) selection coordinates
* @param {Object[]} coordsArr
* @returns {Object}
*/
getCornerCoords: function (coordsArr) {
function mapProp(func, array, prop) {
function getProp(el) {
return el[prop];
}
if (Array.prototype.map) {
return func.apply(Math, array.map(getProp));
}
return func.apply(Math, $.map(array, getProp));
}
return {
TL: {
row: mapProp(Math.min, coordsArr, "row"),
col: mapProp(Math.min, coordsArr, "col")
},
BR: {
row: mapProp(Math.max, coordsArr, "row"),
col: mapProp(Math.max, coordsArr, "col")
}
};
},
/**
* Returns array of td objects given start and end coordinates
*/
getCellsAtCoords: function (start, end) {
var corners = grid.getCornerCoords([start, end]);
var r, c, output = [];
for (r = corners.TL.row; r <= corners.BR.row; r++) {
for (c = corners.TL.col; c <= corners.BR.col; c++) {
output.push(instance.view.getCellAtCoords({
row: r,
col: c
}));
}
}
return output;
}
};
this.selection = selection = { //this public assignment is only temporary
inProgress: false,
/**
* Sets inProgress to true. This enables onSelectionEnd and onSelectionEndByProp to function as desired
*/
begin: function () {
instance.selection.inProgress = true;
},
/**
* Sets inProgress to false. Triggers onSelectionEnd and onSelectionEndByProp
*/
finish: function () {
var sel = instance.getSelected();
instance.PluginHooks.run("afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]);
instance.PluginHooks.run("afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3]));
instance.selection.inProgress = false;
},
isInProgress: function () {
return instance.selection.inProgress;
},
/**
* Starts selection range on given td object
* @param {Object} coords
*/
setRangeStart: function (coords) {
priv.selStart.coords(coords);
selection.setRangeEnd(coords);
},
/**
* Ends selection range on given td object
* @param {Object} coords
* @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end
*/
setRangeEnd: function (coords, scrollToCell) {
instance.selection.begin();
priv.selEnd.coords(coords);
if (!priv.settings.multiSelect) {
priv.selStart.coords(coords);
}
//set up current selection
instance.view.wt.selections.current.clear();
instance.view.wt.selections.current.add(priv.selStart.arr());
//set up area selection
instance.view.wt.selections.area.clear();
if (selection.isMultiple()) {
instance.view.wt.selections.area.add(priv.selStart.arr());
instance.view.wt.selections.area.add(priv.selEnd.arr());
}
//set up highlight
if (priv.settings.currentRowClassName || priv.settings.currentColClassName) {
instance.view.wt.selections.highlight.clear();
instance.view.wt.selections.highlight.add(priv.selStart.arr());
instance.view.wt.selections.highlight.add(priv.selEnd.arr());
}
//trigger handlers
instance.PluginHooks.run("afterSelection", priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col());
instance.PluginHooks.run("afterSelectionByProp", priv.selStart.row(), datamap.colToProp(priv.selStart.col()), priv.selEnd.row(), datamap.colToProp(priv.selEnd.col()));
if (scrollToCell !== false) {
instance.view.scrollViewport(coords);
}
selection.refreshBorders();
},
/**
* Destroys editor, redraws borders around cells, prepares editor
* @param {Boolean} revertOriginal
* @param {Boolean} keepEditor
*/
refreshBorders: function (revertOriginal, keepEditor) {
if (!keepEditor) {
editorManager.destroyEditor(revertOriginal);
}
instance.view.render();
if (selection.isSelected() && !keepEditor) {
editorManager.prepareEditor();
}
},
/**
* Returns information if we have a multiselection
* @return {Boolean}
*/
isMultiple: function () {
return !(priv.selEnd.col() === priv.selStart.col() && priv.selEnd.row() === priv.selStart.row());
},
/**
* Selects cell relative to current cell (if possible)
*/
transformStart: function (rowDelta, colDelta, force) {
if (priv.selStart.row() + rowDelta > instance.countRows() - 1) {
if (force && priv.settings.minSpareRows > 0) {
instance.alter("insert_row", instance.countRows());
}
else if (priv.settings.autoWrapCol) {
rowDelta = 1 - instance.countRows();
colDelta = priv.selStart.col() + colDelta == instance.countCols() - 1 ? 1 - instance.countCols() : 1;
}
}
else if (priv.settings.autoWrapCol && priv.selStart.row() + rowDelta < 0 && priv.selStart.col() + colDelta >= 0) {
rowDelta = instance.countRows() - 1;
colDelta = priv.selStart.col() + colDelta == 0 ? instance.countCols() - 1 : -1;
}
if (priv.selStart.col() + colDelta > instance.countCols() - 1) {
if (force && priv.settings.minSpareCols > 0) {
instance.alter("insert_col", instance.countCols());
}
else if (priv.settings.autoWrapRow) {
rowDelta = priv.selStart.row() + rowDelta == instance.countRows() - 1 ? 1 - instance.countRows() : 1;
colDelta = 1 - instance.countCols();
}
}
else if (priv.settings.autoWrapRow && priv.selStart.col() + colDelta < 0 && priv.selStart.row() + rowDelta >= 0) {
rowDelta = priv.selStart.row() + rowDelta == 0 ? instance.countRows() - 1 : -1;
colDelta = instance.countCols() - 1;
}
var totalRows = instance.countRows();
var totalCols = instance.countCols();
var coords = {
row: priv.selStart.row() + rowDelta,
col: priv.selStart.col() + colDelta
};
if (coords.row < 0) {
coords.row = 0;
}
else if (coords.row > 0 && coords.row >= totalRows) {
coords.row = totalRows - 1;
}
if (coords.col < 0) {
coords.col = 0;
}
else if (coords.col > 0 && coords.col >= totalCols) {
coords.col = totalCols - 1;
}
selection.setRangeStart(coords);
},
/**
* Sets selection end cell relative to current selection end cell (if possible)
*/
transformEnd: function (rowDelta, colDelta) {
if (priv.selEnd.exists()) {
var totalRows = instance.countRows();
var totalCols = instance.countCols();
var coords = {
row: priv.selEnd.row() + rowDelta,
col: priv.selEnd.col() + colDelta
};
if (coords.row < 0) {
coords.row = 0;
}
else if (coords.row > 0 && coords.row >= totalRows) {
coords.row = totalRows - 1;
}
if (coords.col < 0) {
coords.col = 0;
}
else if (coords.col > 0 && coords.col >= totalCols) {
coords.col = totalCols - 1;
}
selection.setRangeEnd(coords);
}
},
/**
* Returns true if currently there is a selection on screen, false otherwise
* @return {Boolean}
*/
isSelected: function () {
return priv.selEnd.exists();
},
/**
* Returns true if coords is within current selection coords
* @return {Boolean}
*/
inInSelection: function (coords) {
if (!selection.isSelected()) {
return false;
}
var sel = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col);
},
/**
* Deselects all selected cells
*/
deselect: function () {
if (!selection.isSelected()) {
return;
}
instance.selection.inProgress = false; //needed by HT inception
priv.selEnd = new Handsontable.SelectionPoint(); //create new empty point to remove the existing one
instance.view.wt.selections.current.clear();
instance.view.wt.selections.area.clear();
editorManager.destroyEditor();
selection.refreshBorders();
instance.PluginHooks.run('afterDeselect');
},
/**
* Select all cells
*/
selectAll: function () {
if (!priv.settings.multiSelect) {
return;
}
selection.setRangeStart({
row: 0,
col: 0
});
selection.setRangeEnd({
row: instance.countRows() - 1,
col: instance.countCols() - 1
}, false);
},
/**
* Deletes data from selected cells
*/
empty: function () {
if (!selection.isSelected()) {
return;
}
var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
var r, c, changes = [];
for (r = corners.TL.row; r <= corners.BR.row; r++) {
for (c = corners.TL.col; c <= corners.BR.col; c++) {
if (!instance.getCellMeta(r, c).readOnly) {
changes.push([r, c, '']);
}
}
}
instance.setDataAtCell(changes);
}
};
this.autofill = autofill = { //this public assignment is only temporary
handle: null,
/**
* Create fill handle and fill border objects
*/
init: function () {
if (!autofill.handle) {
autofill.handle = {};
}
else {
autofill.handle.disabled = false;
}
},
/**
* Hide fill handle and fill border permanently
*/
disable: function () {
autofill.handle.disabled = true;
},
/**
* Selects cells down to the last row in the left column, then fills down to that cell
*/
selectAdjacent: function () {
var select, data, r, maxR, c;
if (selection.isMultiple()) {
select = instance.view.wt.selections.area.getCorners();
}
else {
select = instance.view.wt.selections.current.getCorners();
}
data = datamap.getAll();
rows : for (r = select[2] + 1; r < instance.countRows(); r++) {
for (c = select[1]; c <= select[3]; c++) {
if (data[r][c]) {
break rows;
}
}
if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) {
maxR = r;
}
}
if (maxR) {
instance.view.wt.selections.fill.clear();
instance.view.wt.selections.fill.add([select[0], select[1]]);
instance.view.wt.selections.fill.add([maxR, select[3]]);
autofill.apply();
}
},
/**
* Apply fill values to the area in fill border, omitting the selection border
*/
apply: function () {
var drag, select, start, end, _data;
autofill.handle.isDragged = 0;
drag = instance.view.wt.selections.fill.getCorners();
if (!drag) {
return;
}
instance.view.wt.selections.fill.clear();
if (selection.isMultiple()) {
select = instance.view.wt.selections.area.getCorners();
}
else {
select = instance.view.wt.selections.current.getCorners();
}
if (drag[0] === select[0] && drag[1] < select[1]) {
start = {
row: drag[0],
col: drag[1]
};
end = {
row: drag[2],
col: select[1] - 1
};
}
else if (drag[0] === select[0] && drag[3] > select[3]) {
start = {
row: drag[0],
col: select[3] + 1
};
end = {
row: drag[2],
col: drag[3]
};
}
else if (drag[0] < select[0] && drag[1] === select[1]) {
start = {
row: drag[0],
col: drag[1]
};
end = {
row: select[0] - 1,
col: drag[3]
};
}
else if (drag[2] > select[2] && drag[1] === select[1]) {
start = {
row: select[2] + 1,
col: drag[1]
};
end = {
row: drag[2],
col: drag[3]
};
}
if (start) {
_data = SheetClip.parse(datamap.getText(priv.selStart.coords(), priv.selEnd.coords()));
instance.PluginHooks.run('beforeAutofill', start, end, _data);
grid.populateFromArray(start, _data, end, 'autofill');
selection.setRangeStart({row: drag[0], col: drag[1]});
selection.setRangeEnd({row: drag[2], col: drag[3]});
}
/*else {
//reset to avoid some range bug
selection.refreshBorders();
}*/
},
/**
* Show fill border
*/
showBorder: function (coords) {
coords.row = coords[0];
coords.col = coords[1];
var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) {
coords = [coords.row, corners.BR.col];
}
else if (priv.settings.fillHandle !== 'vertical') {
coords = [corners.BR.row, coords.col];
}
else {
return; //wrong direction
}
instance.view.wt.selections.fill.clear();
instance.view.wt.selections.fill.add([priv.selStart.coords().row, priv.selStart.coords().col]);
instance.view.wt.selections.fill.add([priv.selEnd.coords().row, priv.selEnd.coords().col]);
instance.view.wt.selections.fill.add(coords);
instance.view.render();
}
};
this.init = function () {
instance.PluginHooks.run('beforeInit');
this.view = new Handsontable.TableView(this);
editorManager = new Handsontable.EditorManager(instance, priv, selection, datamap);
this.updateSettings(priv.settings, true);
this.parseSettingsFromDOM();
this.forceFullRender = true; //used when data was changed
this.view.render();
if (typeof priv.firstRun === 'object') {
instance.PluginHooks.run('afterChange', priv.firstRun[0], priv.firstRun[1]);
priv.firstRun = false;
}
instance.PluginHooks.run('afterInit');
};
function ValidatorsQueue() { //moved this one level up so it can be used in any function here. Probably this should be moved to a separate file
var resolved = false;
return {
validatorsInQueue: 0,
addValidatorToQueue: function () {
this.validatorsInQueue++;
resolved = false;
},
removeValidatorFormQueue: function () {
this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1;
this.checkIfQueueIsEmpty();
},
onQueueEmpty: function () {
},
checkIfQueueIsEmpty: function () {
if (this.validatorsInQueue == 0 && resolved == false) {
resolved = true;
this.onQueueEmpty();
}
}
};
}
function validateChanges(changes, source, callback) {
var waitingForValidator = new ValidatorsQueue();
waitingForValidator.onQueueEmpty = resolve;
for (var i = changes.length - 1; i >= 0; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
}
else {
var row = changes[i][0];
var col = datamap.propToCol(changes[i][1]);
var logicalCol = instance.runHooksAndReturn('modifyCol', col); //column order may have changes, so we need to translate physical col index (stored in datasource) to logical (displayed to user)
var cellProperties = instance.getCellMeta(row, logicalCol);
if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') {
if (changes[i][3].length > 0 && /^-?[\d\s]*\.?\d*$/.test(changes[i][3])) {
changes[i][3] = numeral().unformat(changes[i][3] || '0'); //numeral cannot unformat empty string
}
}
if (instance.getCellValidator(cellProperties)) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(changes[i][3], cellProperties, (function (i, cellProperties) {
return function (result) {
if (typeof result !== 'boolean') {
throw new Error("Validation error: result is not boolean");
}
if (result === false && cellProperties.allowInvalid === false) {
changes.splice(i, 1); // cancel the change
cellProperties.valid = true; // we cancelled the change, so cell value is still valid
--i;
}
waitingForValidator.removeValidatorFormQueue();
}
})(i, cellProperties)
, source);
}
}
}
waitingForValidator.checkIfQueueIsEmpty();
function resolve() {
var beforeChangeResult;
if (changes.length) {
beforeChangeResult = instance.PluginHooks.execute("beforeChange", changes, source);
if (typeof beforeChangeResult === 'function') {
$.when(result).then(function () {
callback(); //called when async validators and async beforeChange are resolved
});
}
else if (beforeChangeResult === false) {
changes.splice(0, changes.length); //invalidate all changes (remove everything from array)
}
}
if (typeof beforeChangeResult !== 'function') {
callback(); //called when async validators are resolved and beforeChange was not async
}
}
}
/**
* Internal function to apply changes. Called after validateChanges
* @param {Array} changes Array in form of [row, prop, oldValue, newValue]
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
function applyChanges(changes, source) {
var i = changes.length - 1;
if (i < 0) {
return;
}
for (; 0 <= i; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
continue;
}
if (priv.settings.minSpareRows) {
while (changes[i][0] > instance.countRows() - 1) {
datamap.createRow();
}
}
if (instance.dataType === 'array' && priv.settings.minSpareCols) {
while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) {
datamap.createCol();
}
}
datamap.set(changes[i][0], changes[i][1], changes[i][3]);
}
instance.forceFullRender = true; //used when data was changed
grid.adjustRowsAndCols();
selection.refreshBorders(null, true);
instance.PluginHooks.run('afterChange', changes, source || 'edit');
}
this.validateCell = function (value, cellProperties, callback, source) {
var validator = instance.getCellValidator(cellProperties);
if (Object.prototype.toString.call(validator) === '[object RegExp]') {
validator = (function (validator) {
return function (value, callback) {
callback(validator.test(value));
}
})(validator);
}
if (typeof validator == 'function') {
value = instance.PluginHooks.execute("beforeValidate", value, cellProperties.row, cellProperties.prop, source);
// To provide consistent behaviour, validation should be always asynchronous
setTimeout(function () {
validator.call(cellProperties, value, function (valid) {
cellProperties.valid = valid;
valid = instance.PluginHooks.execute("afterValidate", valid, value, cellProperties.row, cellProperties.prop, source);
callback(valid);
});
});
} else { //resolve callback even if validator function was not found
cellProperties.valid = true;
callback(true);
}
};
function setDataInputToArray(row, prop_or_col, value) {
if (typeof row === "object") { //is it an array of changes
return row;
}
else if ($.isPlainObject(value)) { //backwards compatibility
return value;
}
else {
return [
[row, prop_or_col, value]
];
}
}
/**
* Set data at given cell
* @public
* @param {Number|Array} row or array of changes in format [[row, col, value], ...]
* @param {Number|String} col or source String
* @param {String} value
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
this.setDataAtCell = function (row, col, value, source) {
var input = setDataInputToArray(row, col, value)
, i
, ilen
, changes = []
, prop;
for (i = 0, ilen = input.length; i < ilen; i++) {
if (typeof input[i] !== 'object') {
throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter');
}
if (typeof input[i][1] !== 'number') {
throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`');
}
prop = datamap.colToProp(input[i][1]);
changes.push([
input[i][0],
prop,
datamap.get(input[i][0], prop),
input[i][2]
]);
}
if (!source && typeof row === "object") {
source = col;
}
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Set data at given row property
* @public
* @param {Number|Array} row or array of changes in format [[row, prop, value], ...]
* @param {String} prop or source String
* @param {String} value
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
this.setDataAtRowProp = function (row, prop, value, source) {
var input = setDataInputToArray(row, prop, value)
, i
, ilen
, changes = [];
for (i = 0, ilen = input.length; i < ilen; i++) {
changes.push([
input[i][0],
input[i][1],
datamap.get(input[i][0], input[i][1]),
input[i][2]
]);
}
if (!source && typeof row === "object") {
source = prop;
}
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Listen to document body keyboard input
*/
this.listen = function () {
Handsontable.activeGuid = instance.guid;
if (document.activeElement && document.activeElement !== document.body) {
document.activeElement.blur();
}
else if (!document.activeElement) { //IE
document.body.focus();
}
};
/**
* Stop listening to document body keyboard input
*/
this.unlisten = function () {
Handsontable.activeGuid = null;
};
/**
* Returns true if current Handsontable instance is listening on document body keyboard input
*/
this.isListening = function () {
return Handsontable.activeGuid === instance.guid;
};
/**
* Destroys current editor, renders and selects current cell. If revertOriginal != true, edited data is saved
* @param {Boolean} revertOriginal
*/
this.destroyEditor = function (revertOriginal) {
selection.refreshBorders(revertOriginal);
};
/**
* Populate cells at position with 2d array
* @param {Number} row Start row
* @param {Number} col Start column
* @param {Array} input 2d array
* @param {Number=} endRow End row (use when you want to cut input when certain row is reached)
* @param {Number=} endCol End column (use when you want to cut input when certain column is reached)
* @param {String=} [source="populateFromArray"]
* @param {String=} [method="overwrite"]
* @return {Object|undefined} ending td in pasted area (only if any cell was changed)
*/
this.populateFromArray = function (row, col, input, endRow, endCol, source, method) {
if (!(typeof input === 'object' && typeof input[0] === 'object')) {
throw new Error("populateFromArray parameter `input` must be an array of arrays"); //API changed in 0.9-beta2, let's check if you use it correctly
}
return grid.populateFromArray({row: row, col: col}, input, typeof endRow === 'number' ? {row: endRow, col: endCol} : null, source, method);
};
/**
* Adds/removes data from the column
* @param {Number} col Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
this.spliceCol = function (col, index, amount/*, elements... */) {
return datamap.spliceCol.apply(datamap, arguments);
};
/**
* Adds/removes data from the row
* @param {Number} row Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
this.spliceRow = function (row, index, amount/*, elements... */) {
return datamap.spliceRow.apply(datamap, arguments);
};
/**
* Returns the top left (TL) and bottom right (BR) selection coordinates
* @param {Object[]} coordsArr
* @returns {Object}
*/
this.getCornerCoords = function (coordsArr) {
return grid.getCornerCoords(coordsArr);
};
/**
* Returns current selection. Returns undefined if there is no selection.
* @public
* @return {Array} [`startRow`, `startCol`, `endRow`, `endCol`]
*/
this.getSelected = function () { //https://github.com/warpech/jquery-handsontable/issues/44 //cjl
if (selection.isSelected()) {
return [priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()];
}
};
/**
* Parse settings from DOM and CSS
* @public
*/
this.parseSettingsFromDOM = function () {
var overflow = this.rootElement.css('overflow');
if (overflow === 'scroll' || overflow === 'auto') {
this.rootElement[0].style.overflow = 'visible';
priv.settingsFromDOM.overflow = overflow;
}
else if (priv.settings.width === void 0 || priv.settings.height === void 0) {
priv.settingsFromDOM.overflow = 'auto';
}
if (priv.settings.width === void 0) {
priv.settingsFromDOM.width = this.rootElement.width();
}
else {
priv.settingsFromDOM.width = void 0;
}
priv.settingsFromDOM.height = void 0;
if (priv.settings.height === void 0) {
if (priv.settingsFromDOM.overflow === 'scroll' || priv.settingsFromDOM.overflow === 'auto') {
//this needs to read only CSS/inline style and not actual height
//so we need to call getComputedStyle on cloned container
var clone = this.rootElement[0].cloneNode(false);
var parent = this.rootElement[0].parentNode;
if (parent) {
clone.removeAttribute('id');
parent.appendChild(clone);
var computedHeight = parseInt(window.getComputedStyle(clone, null).getPropertyValue('height'), 10);
if(isNaN(computedHeight) && clone.currentStyle){
computedHeight = parseInt(clone.currentStyle.height, 10)
}
if (computedHeight > 0) {
priv.settingsFromDOM.height = computedHeight;
}
parent.removeChild(clone);
}
}
}
};
/**
* Render visible data
* @public
*/
this.render = function () {
if (instance.view) {
instance.forceFullRender = true; //used when data was changed
instance.parseSettingsFromDOM();
selection.refreshBorders(null, true);
}
};
/**
* Load data from array
* @public
* @param {Array} data
*/
this.loadData = function (data) {
if (typeof data === 'object' && data !== null) {
if (!(data.push && data.splice)) { //check if data is array. Must use duck-type check so Backbone Collections also pass it
//when data is not an array, attempt to make a single-row array of it
data = [data];
}
}
else if(data === null) {
data = [];
var row;
for (var r = 0, rlen = priv.settings.startRows; r < rlen; r++) {
row = [];
for (var c = 0, clen = priv.settings.startCols; c < clen; c++) {
row.push(null);
}
data.push(row);
}
}
else {
throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)");
}
priv.isPopulated = false;
GridSettings.prototype.data = data;
if (priv.settings.dataSchema instanceof Array || data[0] instanceof Array) {
instance.dataType = 'array';
}
else if (typeof priv.settings.dataSchema === 'function') {
instance.dataType = 'function';
}
else {
instance.dataType = 'object';
}
datamap = new Handsontable.DataMap(instance, priv, GridSettings);
clearCellSettingCache();
grid.adjustRowsAndCols();
instance.PluginHooks.run('afterLoadData');
if (priv.firstRun) {
priv.firstRun = [null, 'loadData'];
}
else {
instance.PluginHooks.run('afterChange', null, 'loadData');
instance.render();
}
priv.isPopulated = true;
function clearCellSettingCache() {
priv.cellSettings.length = 0;
}
};
/**
* Return the current data object (the same that was passed by `data` configuration option or `loadData` method). Optionally you can provide cell range `r`, `c`, `r2`, `c2` to get only a fragment of grid data
* @public
* @param {Number} r (Optional) From row
* @param {Number} c (Optional) From col
* @param {Number} r2 (Optional) To row
* @param {Number} c2 (Optional) To col
* @return {Array|Object}
*/
this.getData = function (r, c, r2, c2) {
if (typeof r === 'undefined') {
return datamap.getAll();
}
else {
return datamap.getRange({row: r, col: c}, {row: r2, col: c2}, datamap.DESTINATION_RENDERER);
}
};
this.getCopyableData = function (startRow, startCol, endRow, endCol) {
return datamap.getCopyableText({row: startRow, col: startCol}, {row: endRow, col: endCol});
}
/**
* Update settings
* @public
*/
this.updateSettings = function (settings, init) {
var i, clen;
if (typeof settings.rows !== "undefined") {
throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?");
}
if (typeof settings.cols !== "undefined") {
throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?");
}
for (i in settings) {
if (i === 'data') {
continue; //loadData will be triggered later
}
else {
if (instance.PluginHooks.hooks[i] !== void 0 || instance.PluginHooks.legacy[i] !== void 0) {
if (typeof settings[i] === 'function' || Handsontable.helper.isArray(settings[i])) {
instance.PluginHooks.add(i, settings[i]);
}
}
else {
// Update settings
if (!init && settings.hasOwnProperty(i)) {
GridSettings.prototype[i] = settings[i];
}
//launch extensions
if (Handsontable.extension[i]) {
priv.extensions[i] = new Handsontable.extension[i](instance, settings[i]);
}
}
}
}
// Load data or create data map
if (settings.data === void 0 && priv.settings.data === void 0) {
instance.loadData(null); //data source created just now
}
else if (settings.data !== void 0) {
instance.loadData(settings.data); //data source given as option
}
else if (settings.columns !== void 0) {
datamap.createMap();
}
// Init columns constructors configuration
clen = instance.countCols();
//Clear cellSettings cache
priv.cellSettings.length = 0;
if (clen > 0) {
var proto, column;
for (i = 0; i < clen; i++) {
priv.columnSettings[i] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts);
// shortcut for prototype
proto = priv.columnSettings[i].prototype;
// Use settings provided by user
if (GridSettings.prototype.columns) {
column = GridSettings.prototype.columns[i];
Handsontable.helper.extend(proto, column);
Handsontable.helper.extend(proto, expandType(column));
}
}
}
if (typeof settings.fillHandle !== "undefined") {
if (autofill.handle && settings.fillHandle === false) {
autofill.disable();
}
else if (!autofill.handle && settings.fillHandle !== false) {
autofill.init();
}
}
if (typeof settings.className !== "undefined") {
if (GridSettings.prototype.className) {
instance.rootElement.removeClass(GridSettings.prototype.className);
}
if (settings.className) {
instance.rootElement.addClass(settings.className);
}
}
if (!init) {
instance.PluginHooks.run('afterUpdateSettings');
}
grid.adjustRowsAndCols();
if (instance.view && !priv.firstRun) {
instance.forceFullRender = true; //used when data was changed
selection.refreshBorders(null, true);
}
};
this.getValue = function () {
var sel = instance.getSelected();
if (GridSettings.prototype.getValue) {
if (typeof GridSettings.prototype.getValue === 'function') {
return GridSettings.prototype.getValue.call(instance);
}
else if (sel) {
return instance.getData()[sel[0]][GridSettings.prototype.getValue];
}
}
else if (sel) {
return instance.getDataAtCell(sel[0], sel[1]);
}
};
function expandType(obj) {
if (!obj.hasOwnProperty('type')) return; //ignore obj.prototype.type
var type, expandedType = {};
if (typeof obj.type === 'object') {
type = obj.type;
}
else if (typeof obj.type === 'string') {
type = Handsontable.cellTypes[obj.type];
if (type === void 0) {
throw new Error('You declared cell type "' + obj.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
}
}
for (var i in type) {
if (type.hasOwnProperty(i) && !obj.hasOwnProperty(i)) {
expandedType[i] = type[i];
}
}
return expandedType;
}
/**
* Returns current settings object
* @return {Object}
*/
this.getSettings = function () {
return priv.settings;
};
/**
* Returns current settingsFromDOM object
* @return {Object}
*/
this.getSettingsFromDOM = function () {
return priv.settingsFromDOM;
};
/**
* Clears grid
* @public
*/
this.clear = function () {
selection.selectAll();
selection.empty();
};
/**
* Inserts or removes rows and columns
* @param {String} action See grid.alter for possible values
* @param {Number} index
* @param {Number} amount
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
* @public
*/
this.alter = function (action, index, amount, source, keepEmptyRows) {
grid.alter(action, index, amount, source, keepEmptyRows);
};
/**
* Returns <td> element corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @public
* @return {Element}
*/
this.getCell = function (row, col) {
return instance.view.getCellAtCoords({row: row, col: col});
};
/**
* Returns property name associated with column number
* @param {Number} col
* @public
* @return {String}
*/
this.colToProp = function (col) {
return datamap.colToProp(col);
};
/**
* Returns column number associated with property name
* @param {String} prop
* @public
* @return {Number}
*/
this.propToCol = function (prop) {
return datamap.propToCol(prop);
};
/**
* Return value at `row`, `col`
* @param {Number} row
* @param {Number} col
* @public
* @return value (mixed data type)
*/
this.getDataAtCell = function (row, col) {
return datamap.get(row, datamap.colToProp(col));
};
/**
* Return value at `row`, `prop`
* @param {Number} row
* @param {String} prop
* @public
* @return value (mixed data type)
*/
this.getDataAtRowProp = function (row, prop) {
return datamap.get(row, prop);
};
/**
* Return value at `col`
* @param {Number} col
* @public
* @return value (mixed data type)
*/
this.getDataAtCol = function (col) {
return [].concat.apply([], datamap.getRange({row: 0, col: col}, {row: priv.settings.data.length - 1, col: col}, datamap.DESTINATION_RENDERER));
};
/**
* Return value at `prop`
* @param {String} prop
* @public
* @return value (mixed data type)
*/
this.getDataAtProp = function (prop) {
return [].concat.apply([], datamap.getRange({row: 0, col: datamap.propToCol(prop)}, {row: priv.settings.data.length - 1, col: datamap.propToCol(prop)}, datamap.DESTINATION_RENDERER));
};
/**
* Return value at `row`
* @param {Number} row
* @public
* @return value (mixed data type)
*/
this.getDataAtRow = function (row) {
return priv.settings.data[row];
};
/**
* Returns cell meta data object corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @public
* @return {Object}
*/
this.getCellMeta = function (row, col) {
var prop = datamap.colToProp(col)
, cellProperties;
row = translateRowIndex(row);
col = translateColIndex(col);
if ("undefined" === typeof priv.columnSettings[col]) {
priv.columnSettings[col] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts);
}
if (!priv.cellSettings[row]) {
priv.cellSettings[row] = [];
}
if (!priv.cellSettings[row][col]) {
priv.cellSettings[row][col] = new priv.columnSettings[col]();
}
cellProperties = priv.cellSettings[row][col]; //retrieve cellProperties from cache
cellProperties.row = row;
cellProperties.col = col;
cellProperties.prop = prop;
cellProperties.instance = instance;
instance.PluginHooks.run('beforeGetCellMeta', row, col, cellProperties);
Handsontable.helper.extend(cellProperties, expandType(cellProperties)); //for `type` added in beforeGetCellMeta
if (cellProperties.cells) {
var settings = cellProperties.cells.call(cellProperties, row, col, prop);
if (settings) {
Handsontable.helper.extend(cellProperties, settings);
Handsontable.helper.extend(cellProperties, expandType(settings)); //for `type` added in cells
}
}
instance.PluginHooks.run('afterGetCellMeta', row, col, cellProperties);
return cellProperties;
/**
* If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied)
* we need to translate logical (stored) row index to physical (displayed) index.
* @param row - original row index
* @returns {int} translated row index
*/
function translateRowIndex(row){
var getVars = {row: row};
instance.PluginHooks.execute('beforeGet', getVars);
return getVars.row;
}
/**
* If displayed columns order is different than the order of columns stored in memory (i.e. column were moved using manualColumnMove plugin)
* we need to translate logical (stored) column index to physical (displayed) index.
* @param col - original column index
* @returns {int} - translated column index
*/
function translateColIndex(col){
return Handsontable.PluginHooks.execute(instance, 'modifyCol', col); // warning: this must be done after datamap.colToProp
}
};
var rendererLookup = Handsontable.helper.cellMethodLookupFactory('renderer');
this.getCellRenderer = function (row, col) {
var renderer = rendererLookup.call(this, row, col);
return Handsontable.renderers.getRenderer(renderer);
};
this.getCellEditor = Handsontable.helper.cellMethodLookupFactory('editor');
this.getCellValidator = Handsontable.helper.cellMethodLookupFactory('validator');
/**
* Validates all cells using their validator functions and calls callback when finished. Does not render the view
* @param callback
*/
this.validateCells = function (callback) {
var waitingForValidator = new ValidatorsQueue();
waitingForValidator.onQueueEmpty = callback;
var i = instance.countRows() - 1;
while (i >= 0) {
var j = instance.countCols() - 1;
while (j >= 0) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function () {
waitingForValidator.removeValidatorFormQueue();
}, 'validateCells');
j--;
}
i--;
}
waitingForValidator.checkIfQueueIsEmpty();
};
/**
* Return array of row headers (if they are enabled). If param `row` given, return header at given row as string
* @param {Number} row (Optional)
* @return {Array|String}
*/
this.getRowHeader = function (row) {
if (row === void 0) {
var out = [];
for (var i = 0, ilen = instance.countRows(); i < ilen; i++) {
out.push(instance.getRowHeader(i));
}
return out;
}
else if (Object.prototype.toString.call(priv.settings.rowHeaders) === '[object Array]' && priv.settings.rowHeaders[row] !== void 0) {
return priv.settings.rowHeaders[row];
}
else if (typeof priv.settings.rowHeaders === 'function') {
return priv.settings.rowHeaders(row);
}
else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') {
return row + 1;
}
else {
return priv.settings.rowHeaders;
}
};
/**
* Returns information of this table is configured to display row headers
* @returns {boolean}
*/
this.hasRowHeaders = function () {
return !!priv.settings.rowHeaders;
};
/**
* Returns information of this table is configured to display column headers
* @returns {boolean}
*/
this.hasColHeaders = function () {
if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) { //Polymer has empty value = null
return !!priv.settings.colHeaders;
}
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
if (instance.getColHeader(i)) {
return true;
}
}
return false;
};
/**
* Return array of column headers (if they are enabled). If param `col` given, return header at given column as string
* @param {Number} col (Optional)
* @return {Array|String}
*/
this.getColHeader = function (col) {
if (col === void 0) {
var out = [];
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
out.push(instance.getColHeader(i));
}
return out;
}
else {
col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col);
if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) {
return priv.settings.columns[col].title;
}
else if (Object.prototype.toString.call(priv.settings.colHeaders) === '[object Array]' && priv.settings.colHeaders[col] !== void 0) {
return priv.settings.colHeaders[col];
}
else if (typeof priv.settings.colHeaders === 'function') {
return priv.settings.colHeaders(col);
}
else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') {
return Handsontable.helper.spreadsheetColumnLabel(col);
}
else {
return priv.settings.colHeaders;
}
}
};
/**
* Return column width from settings (no guessing). Private use intended
* @param {Number} col
* @return {Number}
*/
this._getColWidthFromSettings = function (col) {
var cellProperties = instance.getCellMeta(0, col);
var width = cellProperties.width;
if (width === void 0 || width === priv.settings.width) {
width = cellProperties.colWidths;
}
if (width !== void 0 && width !== null) {
switch (typeof width) {
case 'object': //array
width = width[col];
break;
case 'function':
width = width(col);
break;
}
if (typeof width === 'string') {
width = parseInt(width, 10);
}
}
return width;
};
/**
* Return column width
* @param {Number} col
* @return {Number}
*/
this.getColWidth = function (col) {
col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col);
var response = {
width: instance._getColWidthFromSettings(col)
};
if (!response.width) {
response.width = 50;
}
instance.PluginHooks.run('afterGetColWidth', col, response);
return response.width;
};
/**
* Return total number of rows in grid
* @return {Number}
*/
this.countRows = function () {
return priv.settings.data.length;
};
/**
* Return total number of columns in grid
* @return {Number}
*/
this.countCols = function () {
if (instance.dataType === 'object' || instance.dataType === 'function') {
if (priv.settings.columns && priv.settings.columns.length) {
return priv.settings.columns.length;
}
else {
return datamap.colToPropCache.length;
}
}
else if (instance.dataType === 'array') {
if (priv.settings.columns && priv.settings.columns.length) {
return priv.settings.columns.length;
}
else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) {
return priv.settings.data[0].length;
}
else {
return 0;
}
}
};
/**
* Return index of first visible row
* @return {Number}
*/
this.rowOffset = function () {
return instance.view.wt.getSetting('offsetRow');
};
/**
* Return index of first visible column
* @return {Number}
*/
this.colOffset = function () {
return instance.view.wt.getSetting('offsetColumn');
};
/**
* Return number of visible rows. Returns -1 if table is not visible
* @return {Number}
*/
this.countVisibleRows = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.rowStrategy.countVisible() : -1;
};
/**
* Return number of visible columns. Returns -1 if table is not visible
* @return {Number}
*/
this.countVisibleCols = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.columnStrategy.countVisible() : -1;
};
/**
* Return number of empty rows
* @return {Boolean} ending If true, will only count empty rows at the end of the data source
*/
this.countEmptyRows = function (ending) {
var i = instance.countRows() - 1
, empty = 0;
while (i >= 0) {
datamap.get(i, 0);
if (instance.isEmptyRow(datamap.getVars.row)) {
empty++;
}
else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Return number of empty columns
* @return {Boolean} ending If true, will only count empty columns at the end of the data source row
*/
this.countEmptyCols = function (ending) {
if (instance.countRows() < 1) {
return 0;
}
var i = instance.countCols() - 1
, empty = 0;
while (i >= 0) {
if (instance.isEmptyCol(i)) {
empty++;
}
else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Return true if the row at the given index is empty, false otherwise
* @param {Number} r Row index
* @return {Boolean}
*/
this.isEmptyRow = function (r) {
return priv.settings.isEmptyRow.call(instance, r);
};
/**
* Return true if the column at the given index is empty, false otherwise
* @param {Number} c Column index
* @return {Boolean}
*/
this.isEmptyCol = function (c) {
return priv.settings.isEmptyCol.call(instance, c);
};
/**
* Selects cell on grid. Optionally selects range to another cell
* @param {Number} row
* @param {Number} col
* @param {Number} [endRow]
* @param {Number} [endCol]
* @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to the selection
* @public
* @return {Boolean}
*/
this.selectCell = function (row, col, endRow, endCol, scrollToCell) {
if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) {
return false;
}
if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
return false;
}
if (typeof endRow !== "undefined") {
if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
return false;
}
if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
return false;
}
}
priv.selStart.coords({row: row, col: col});
if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) {
document.activeElement.blur(); //needed or otherwise prepare won't focus the cell. selectionSpec tests this (should move focus to selected cell)
}
instance.listen();
if (typeof endRow === "undefined") {
selection.setRangeEnd({row: row, col: col}, scrollToCell);
}
else {
selection.setRangeEnd({row: endRow, col: endCol}, scrollToCell);
}
instance.selection.finish();
return true;
};
this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) {
arguments[1] = datamap.propToCol(arguments[1]);
if (typeof arguments[3] !== "undefined") {
arguments[3] = datamap.propToCol(arguments[3]);
}
return instance.selectCell.apply(instance, arguments);
};
/**
* Deselects current sell selection on grid
* @public
*/
this.deselectCell = function () {
selection.deselect();
};
/**
* Remove grid from DOM
* @public
*/
this.destroy = function () {
instance.clearTimeouts();
if (instance.view) { //in case HT is destroyed before initialization has finished
instance.view.wt.destroy();
}
instance.rootElement.empty();
instance.rootElement.removeData('handsontable');
instance.rootElement.off('.handsontable');
$(window).off('.' + instance.guid);
$document.off('.' + instance.guid);
$body.off('.' + instance.guid);
instance.PluginHooks.run('afterDestroy');
};
/**
* Returns active editor object
* @returns {Object}
*/
this.getActiveEditor = function(){
return editorManager.getActiveEditor();
};
/**
* Return Handsontable instance
* @public
* @return {Object}
*/
this.getInstance = function () {
return instance.rootElement.data("handsontable");
};
(function () {
// Create new instance of plugin hooks
instance.PluginHooks = new Handsontable.PluginHookClass();
// Upgrade methods to call of global PluginHooks instance
var _run = instance.PluginHooks.run
, _exe = instance.PluginHooks.execute;
instance.PluginHooks.run = function (key, p1, p2, p3, p4, p5) {
_run.call(this, instance, key, p1, p2, p3, p4, p5);
Handsontable.PluginHooks.run(instance, key, p1, p2, p3, p4, p5);
};
instance.PluginHooks.execute = function (key, p1, p2, p3, p4, p5) {
var globalHandlerResult = Handsontable.PluginHooks.execute(instance, key, p1, p2, p3, p4, p5);
var localHandlerResult = _exe.call(this, instance, key, globalHandlerResult, p2, p3, p4, p5);
return typeof localHandlerResult == 'undefined' ? globalHandlerResult : localHandlerResult;
};
// Map old API with new methods
instance.addHook = function () {
instance.PluginHooks.add.apply(instance.PluginHooks, arguments);
};
instance.addHookOnce = function () {
instance.PluginHooks.once.apply(instance.PluginHooks, arguments);
};
instance.removeHook = function () {
instance.PluginHooks.remove.apply(instance.PluginHooks, arguments);
};
instance.runHooks = function () {
instance.PluginHooks.run.apply(instance.PluginHooks, arguments);
};
instance.runHooksAndReturn = function () {
return instance.PluginHooks.execute.apply(instance.PluginHooks, arguments);
};
})();
this.timeouts = {};
/**
* Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called
* @public
*/
this.registerTimeout = function (key, handle, ms) {
clearTimeout(this.timeouts[key]);
this.timeouts[key] = setTimeout(handle, ms || 0);
};
/**
* Clears all known timeouts
* @public
*/
this.clearTimeouts = function () {
for (var key in this.timeouts) {
if (this.timeouts.hasOwnProperty(key)) {
clearTimeout(this.timeouts[key]);
}
}
};
/**
* Handsontable version
*/
this.version = '0.10.3'; //inserted by grunt from package.json
};
var DefaultSettings = function () {};
DefaultSettings.prototype = {
data: void 0,
width: void 0,
height: void 0,
startRows: 5,
startCols: 5,
rowHeaders: null,
colHeaders: null,
minRows: 0,
minCols: 0,
maxRows: Infinity,
maxCols: Infinity,
minSpareRows: 0,
minSpareCols: 0,
multiSelect: true,
fillHandle: true,
fixedRowsTop: 0,
fixedColumnsLeft: 0,
outsideClickDeselects: true,
enterBeginsEditing: true,
enterMoves: {row: 1, col: 0},
tabMoves: {row: 0, col: 1},
autoWrapRow: false,
autoWrapCol: false,
copyRowsLimit: 1000,
copyColsLimit: 1000,
pasteMode: 'overwrite',
currentRowClassName: void 0,
currentColClassName: void 0,
stretchH: 'hybrid',
isEmptyRow: function (r) {
var val;
for (var c = 0, clen = this.countCols(); c < clen; c++) {
val = this.getDataAtCell(r, c);
if (val !== '' && val !== null && typeof val !== 'undefined') {
return false;
}
}
return true;
},
isEmptyCol: function (c) {
var val;
for (var r = 0, rlen = this.countRows(); r < rlen; r++) {
val = this.getDataAtCell(r, c);
if (val !== '' && val !== null && typeof val !== 'undefined') {
return false;
}
}
return true;
},
observeDOMVisibility: true,
allowInvalid: true,
invalidCellClassName: 'htInvalid',
placeholderCellClassName: 'htPlaceholder',
readOnlyCellClassName: 'htDimmed',
fragmentSelection: false,
readOnly: false,
nativeScrollbars: false,
type: 'text',
copyable: true,
debug: false //shows debug overlays in Walkontable
};
Handsontable.DefaultSettings = DefaultSettings;
$.fn.handsontable = function (action) {
var i
, ilen
, args
, output
, userSettings
, $this = this.first() // Use only first element from list
, instance = $this.data('handsontable');
// Init case
if (typeof action !== 'string') {
userSettings = action || {};
if (instance) {
instance.updateSettings(userSettings);
}
else {
instance = new Handsontable.Core($this, userSettings);
$this.data('handsontable', instance);
instance.init();
}
return $this;
}
// Action case
else {
args = [];
if (arguments.length > 1) {
for (i = 1, ilen = arguments.length; i < ilen; i++) {
args.push(arguments[i]);
}
}
if (instance) {
if (typeof instance[action] !== 'undefined') {
output = instance[action].apply(instance, args);
}
else {
throw new Error('Handsontable do not provide action: ' + action);
}
}
return output;
}
};
/**
* Handsontable TableView constructor
* @param {Object} instance
*/
Handsontable.TableView = function (instance) {
var that = this
, $window = $(window)
, $documentElement = $(document.documentElement);
this.instance = instance;
this.settings = instance.getSettings();
this.settingsFromDOM = instance.getSettingsFromDOM();
instance.rootElement.data('originalStyle', instance.rootElement[0].getAttribute('style')); //needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions
// in IE7 getAttribute('style') returns an object instead of a string, but we only support IE8+
instance.rootElement.addClass('handsontable');
var table = document.createElement('TABLE');
table.className = 'htCore';
this.THEAD = document.createElement('THEAD');
table.appendChild(this.THEAD);
this.TBODY = document.createElement('TBODY');
table.appendChild(this.TBODY);
instance.$table = $(table);
instance.rootElement.prepend(instance.$table);
instance.rootElement.on('mousedown.handsontable', function (event) {
if (!that.isTextSelectionAllowed(event.target)) {
clearTextSelection();
event.preventDefault();
window.focus(); //make sure that window that contains HOT is active. Important when HOT is in iframe.
}
});
$documentElement.on('keyup.' + instance.guid, function (event) {
if (instance.selection.isInProgress() && !event.shiftKey) {
instance.selection.finish();
}
});
var isMouseDown;
$documentElement.on('mouseup.' + instance.guid, function (event) {
if (instance.selection.isInProgress() && event.which === 1) { //is left mouse button
instance.selection.finish();
}
isMouseDown = false;
if (instance.autofill.handle && instance.autofill.handle.isDragged) {
if (instance.autofill.handle.isDragged > 1) {
instance.autofill.apply();
}
instance.autofill.handle.isDragged = 0;
}
if (Handsontable.helper.isOutsideInput(document.activeElement)) {
instance.unlisten();
}
});
$documentElement.on('mousedown.' + instance.guid, function (event) {
var next = event.target;
if (next !== that.wt.wtTable.spreader) { //immediate click on "spreader" means click on the right side of vertical scrollbar
while (next !== document.documentElement) {
if (next === null) {
return; //click on something that was a row but now is detached (possibly because your click triggered a rerender)
}
if (next === instance.rootElement[0] || next.nodeName === 'HANDSONTABLE-TABLE') {
return; //click inside container or Web Component (HANDSONTABLE-TABLE is the name of the custom element)
}
next = next.parentNode;
}
}
if (that.settings.outsideClickDeselects) {
instance.deselectCell();
}
else {
instance.destroyEditor();
}
});
instance.rootElement.on('mousedown.handsontable', '.dragdealer', function () {
instance.destroyEditor();
});
instance.$table.on('selectstart', function (event) {
if (that.settings.fragmentSelection) {
return;
}
//https://github.com/warpech/jquery-handsontable/issues/160
//selectstart is IE only event. Prevent text from being selected when performing drag down in IE8
event.preventDefault();
});
var clearTextSelection = function () {
//http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
};
var walkontableConfig = {
debug: function () {
return that.settings.debug;
},
table: table,
stretchH: this.settings.stretchH,
data: instance.getDataAtCell,
totalRows: instance.countRows,
totalColumns: instance.countCols,
nativeScrollbars: this.settings.nativeScrollbars,
offsetRow: 0,
offsetColumn: 0,
width: this.getWidth(),
height: this.getHeight(),
fixedColumnsLeft: function () {
return that.settings.fixedColumnsLeft;
},
fixedRowsTop: function () {
return that.settings.fixedRowsTop;
},
rowHeaders: function () {
return instance.hasRowHeaders() ? [function (index, TH) {
that.appendRowHeader(index, TH);
}] : []
},
columnHeaders: function () {
return instance.hasColHeaders() ? [function (index, TH) {
that.appendColHeader(index, TH);
}] : []
},
columnWidth: instance.getColWidth,
cellRenderer: function (row, col, TD) {
var prop = that.instance.colToProp(col)
, cellProperties = that.instance.getCellMeta(row, col)
, renderer = that.instance.getCellRenderer(cellProperties);
var value = that.instance.getDataAtRowProp(row, prop);
renderer(that.instance, TD, row, col, prop, value, cellProperties);
that.instance.PluginHooks.run('afterRenderer', TD, row, col, prop, value, cellProperties);
},
selections: {
current: {
className: 'current',
border: {
width: 2,
color: '#5292F7',
style: 'solid',
cornerVisible: function () {
return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple()
}
}
},
area: {
className: 'area',
border: {
width: 1,
color: '#89AFF9',
style: 'solid',
cornerVisible: function () {
return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple()
}
}
},
highlight: {
highlightRowClassName: that.settings.currentRowClassName,
highlightColumnClassName: that.settings.currentColClassName
},
fill: {
className: 'fill',
border: {
width: 1,
color: 'red',
style: 'solid'
}
}
},
hideBorderOnMouseDownOver: function () {
return that.settings.fragmentSelection;
},
onCellMouseDown: function (event, coords, TD) {
instance.listen();
isMouseDown = true;
var coordsObj = {row: coords[0], col: coords[1]};
if (event.button === 2 && instance.selection.inInSelection(coordsObj)) { //right mouse button
//do nothing
}
else if (event.shiftKey) {
instance.selection.setRangeEnd(coordsObj);
}
else {
instance.selection.setRangeStart(coordsObj);
}
instance.PluginHooks.run('afterOnCellMouseDown', event, coords, TD);
},
/*onCellMouseOut: function (/*event, coords, TD* /) {
if (isMouseDown && that.settings.fragmentSelection === 'single') {
clearTextSelection(); //otherwise text selection blinks during multiple cells selection
}
},*/
onCellMouseOver: function (event, coords, TD) {
var coordsObj = {row: coords[0], col: coords[1]};
if (isMouseDown) {
/*if (that.settings.fragmentSelection === 'single') {
clearTextSelection(); //otherwise text selection blinks during multiple cells selection
}*/
instance.selection.setRangeEnd(coordsObj);
}
else if (instance.autofill.handle && instance.autofill.handle.isDragged) {
instance.autofill.handle.isDragged++;
instance.autofill.showBorder(coords);
}
instance.PluginHooks.run('afterOnCellMouseOver', event, coords, TD);
},
onCellCornerMouseDown: function (event) {
instance.autofill.handle.isDragged = 1;
event.preventDefault();
instance.PluginHooks.run('afterOnCellCornerMouseDown', event);
},
onCellCornerDblClick: function () {
instance.autofill.selectAdjacent();
},
beforeDraw: function (force) {
that.beforeRender(force);
},
onDraw: function(force){
that.onDraw(force);
},
onScrollVertically: function () {
instance.runHooks('afterScrollVertically');
},
onScrollHorizontally: function () {
instance.runHooks('afterScrollHorizontally');
}
};
instance.PluginHooks.run('beforeInitWalkontable', walkontableConfig);
this.wt = new Walkontable(walkontableConfig);
$window.on('resize.' + instance.guid, function () {
instance.registerTimeout('resizeTimeout', function () {
instance.parseSettingsFromDOM();
var newWidth = that.getWidth();
var newHeight = that.getHeight();
if (walkontableConfig.width !== newWidth || walkontableConfig.height !== newHeight) {
instance.forceFullRender = true;
that.render();
walkontableConfig.width = newWidth;
walkontableConfig.height = newHeight;
}
}, 60);
});
$(that.wt.wtTable.spreader).on('mousedown.handsontable, contextmenu.handsontable', function (event) {
if (event.target === that.wt.wtTable.spreader && event.which === 3) { //right mouse button exactly on spreader means right clickon the right hand side of vertical scrollbar
event.stopPropagation();
}
});
$documentElement.on('click.' + instance.guid, function () {
if (that.settings.observeDOMVisibility) {
if (that.wt.drawInterrupted) {
that.instance.forceFullRender = true;
that.render();
}
}
});
};
Handsontable.TableView.prototype.isTextSelectionAllowed = function (el) {
if ( Handsontable.helper.isInput(el) ) {
return (true);
}
if (this.settings.fragmentSelection && this.wt.wtDom.isChildOf(el, this.TBODY)) {
return (true);
}
return false;
};
Handsontable.TableView.prototype.isCellEdited = function () {
var activeEditor = this.instance.getActiveEditor();
return activeEditor && activeEditor.isOpened();
};
Handsontable.TableView.prototype.getWidth = function () {
var val = this.settings.width !== void 0 ? this.settings.width : this.settingsFromDOM.width;
return typeof val === 'function' ? val() : val;
};
Handsontable.TableView.prototype.getHeight = function () {
var val = this.settings.height !== void 0 ? this.settings.height : this.settingsFromDOM.height;
return typeof val === 'function' ? val() : val;
};
Handsontable.TableView.prototype.beforeRender = function (force) {
if (force) { //force = did Walkontable decide to do full render
this.instance.PluginHooks.run('beforeRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render?
this.wt.update('width', this.getWidth());
this.wt.update('height', this.getHeight());
}
};
Handsontable.TableView.prototype.onDraw = function(force){
if (force) { //force = did Walkontable decide to do full render
this.instance.PluginHooks.run('afterRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render?
}
};
Handsontable.TableView.prototype.render = function () {
this.wt.draw(!this.instance.forceFullRender);
this.instance.forceFullRender = false;
this.instance.rootElement.triggerHandler('render.handsontable');
};
/**
* Returns td object given coordinates
*/
Handsontable.TableView.prototype.getCellAtCoords = function (coords) {
var td = this.wt.wtTable.getCell([coords.row, coords.col]);
if (td < 0) { //there was an exit code (cell is out of bounds)
return null;
}
else {
return td;
}
};
/**
* Scroll viewport to selection
* @param coords
*/
Handsontable.TableView.prototype.scrollViewport = function (coords) {
this.wt.scrollViewport([coords.row, coords.col]);
};
/**
* Append row header to a TH element
* @param row
* @param TH
*/
Handsontable.TableView.prototype.appendRowHeader = function (row, TH) {
if (row > -1) {
this.wt.wtDom.fastInnerHTML(TH, this.instance.getRowHeader(row));
}
else {
var DIV = document.createElement('DIV');
DIV.className = 'relative';
this.wt.wtDom.fastInnerText(DIV, '\u00A0');
this.wt.wtDom.empty(TH);
TH.appendChild(DIV);
}
};
/**
* Append column header to a TH element
* @param col
* @param TH
*/
Handsontable.TableView.prototype.appendColHeader = function (col, TH) {
var DIV = document.createElement('DIV')
, SPAN = document.createElement('SPAN');
DIV.className = 'relative';
SPAN.className = 'colHeader';
this.wt.wtDom.fastInnerHTML(SPAN, this.instance.getColHeader(col));
DIV.appendChild(SPAN);
this.wt.wtDom.empty(TH);
TH.appendChild(DIV);
this.instance.PluginHooks.run('afterGetColHeader', col, TH);
};
/**
* Given a element's left position relative to the viewport, returns maximum element width until the right edge of the viewport (before scrollbar)
* @param {Number} left
* @return {Number}
*/
Handsontable.TableView.prototype.maximumVisibleElementWidth = function (left) {
var rootWidth = this.wt.wtViewport.getWorkspaceWidth();
if(this.settings.nativeScrollbars) {
return rootWidth;
}
return rootWidth - left;
};
/**
* Given a element's top position relative to the viewport, returns maximum element height until the bottom edge of the viewport (before scrollbar)
* @param {Number} top
* @return {Number}
*/
Handsontable.TableView.prototype.maximumVisibleElementHeight = function (top) {
var rootHeight = this.wt.wtViewport.getWorkspaceHeight();
if(this.settings.nativeScrollbars) {
return rootHeight;
}
return rootHeight - top;
};
/**
* Utility to register editors and common namespace for keeping reference to all editor classes
*/
(function (Handsontable) {
'use strict';
function RegisteredEditor(editorClass) {
var clazz, instances;
instances = {};
clazz = editorClass;
this.getInstance = function (hotInstance) {
if (!(hotInstance.guid in instances)) {
instances[hotInstance.guid] = new clazz(hotInstance);
}
return instances[hotInstance.guid];
}
}
var registeredEditorNames = {};
var registeredEditorClasses = new WeakMap();
Handsontable.editors = {
/**
* Registers editor under given name
* @param {String} editorName
* @param {Function} editorClass
*/
registerEditor: function (editorName, editorClass) {
var editor = new RegisteredEditor(editorClass);
if (typeof editorName === "string") {
registeredEditorNames[editorName] = editor;
}
registeredEditorClasses.set(editorClass, editor);
},
/**
* Returns instance (singleton) of editor class
* @param {String|Function} editorName/editorClass
* @returns {Function} editorClass
*/
getEditor: function (editorName, hotInstance) {
var editor;
if (typeof editorName == 'function') {
if (!(registeredEditorClasses.get(editorName))) {
this.registerEditor(null, editorName);
}
editor = registeredEditorClasses.get(editorName);
}
else if (typeof editorName == 'string') {
editor = registeredEditorNames[editorName];
}
else {
throw Error('Only strings and functions can be passed as "editor" parameter ');
}
if (!editor) {
throw Error('No editor registered under name "' + editorName + '"');
}
return editor.getInstance(hotInstance);
}
};
})(Handsontable);
(function(Handsontable){
'use strict';
Handsontable.EditorManager = function(instance, priv, selection){
var that = this;
var $document = $(document);
var keyCodes = Handsontable.helper.keyCode;
var activeEditor;
var init = function () {
function onKeyDown(event) {
if (!instance.isListening()) {
return;
}
if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin
priv.settings.beforeOnKeyDown.call(instance, event);
}
instance.PluginHooks.run('beforeKeyDown', event);
if (!event.isImmediatePropagationStopped()) {
priv.lastKeyCode = event.keyCode;
if (selection.isSelected()) {
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
if (!activeEditor.isWaiting()) {
if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown) {
that.openEditor('');
event.stopPropagation(); //required by HandsontableEditor
return;
}
}
var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart;
switch (event.keyCode) {
case keyCodes.A:
if (ctrlDown) {
selection.selectAll(); //select all cells
event.preventDefault();
event.stopPropagation();
break;
}
case keyCodes.ARROW_UP:
if (that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionUp(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_DOWN:
if (that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionDown(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_RIGHT:
if(that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionRight(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_LEFT:
if(that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionLeft(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.TAB:
var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves;
if (event.shiftKey) {
selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left
}
else {
selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed)
}
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.BACKSPACE:
case keyCodes.DELETE:
selection.empty(event);
that.prepareEditor();
event.preventDefault();
break;
case keyCodes.F2: /* F2 */
that.openEditor();
event.preventDefault(); //prevent Opera from opening Go to Page dialog
break;
case keyCodes.ENTER: /* return/enter */
if(that.isEditorOpened()){
if (activeEditor.state !== Handsontable.EditorState.WAITING){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionAfterEnter(event.shiftKey);
} else {
if (instance.getSettings().enterBeginsEditing){
that.openEditor();
} else {
moveSelectionAfterEnter(event.shiftKey);
}
}
event.preventDefault(); //don't add newline to field
event.stopImmediatePropagation(); //required by HandsontableEditor
break;
case keyCodes.ESCAPE:
if(that.isEditorOpened()){
that.closeEditorAndRestoreOriginalValue(ctrlDown);
}
event.preventDefault();
break;
case keyCodes.HOME:
if (event.ctrlKey || event.metaKey) {
rangeModifier({row: 0, col: priv.selStart.col()});
}
else {
rangeModifier({row: priv.selStart.row(), col: 0});
}
event.preventDefault(); //don't scroll the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.END:
if (event.ctrlKey || event.metaKey) {
rangeModifier({row: instance.countRows() - 1, col: priv.selStart.col()});
}
else {
rangeModifier({row: priv.selStart.row(), col: instance.countCols() - 1});
}
event.preventDefault(); //don't scroll the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.PAGE_UP:
selection.transformStart(-instance.countVisibleRows(), 0);
instance.view.wt.scrollVertical(-instance.countVisibleRows());
instance.view.render();
event.preventDefault(); //don't page up the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.PAGE_DOWN:
selection.transformStart(instance.countVisibleRows(), 0);
instance.view.wt.scrollVertical(instance.countVisibleRows());
instance.view.render();
event.preventDefault(); //don't page down the window
event.stopPropagation(); //required by HandsontableEditor
break;
default:
break;
}
}
}
}
$document.on('keydown.handsontable.' + instance.guid, onKeyDown);
function onDblClick() {
// that.instance.destroyEditor();
that.openEditor();
}
instance.view.wt.update('onCellDblClick', onDblClick);
instance.addHook('afterDestroy', function(){
$document.off('keydown.handsontable.' + instance.guid);
});
function moveSelectionAfterEnter(shiftKey){
var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves;
if (shiftKey) {
selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up
}
else {
selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed)
}
}
function moveSelectionUp(shiftKey){
if (shiftKey) {
selection.transformEnd(-1, 0);
}
else {
selection.transformStart(-1, 0);
}
}
function moveSelectionDown(shiftKey){
if (shiftKey) {
selection.transformEnd(1, 0); //expanding selection down with shift
}
else {
selection.transformStart(1, 0); //move selection down
}
}
function moveSelectionRight(shiftKey){
if (shiftKey) {
selection.transformEnd(0, 1);
}
else {
selection.transformStart(0, 1);
}
}
function moveSelectionLeft(shiftKey){
if (shiftKey) {
selection.transformEnd(0, -1);
}
else {
selection.transformStart(0, -1);
}
}
};
/**
* Destroy current editor, if exists
* @param {Boolean} revertOriginal
*/
this.destroyEditor = function (revertOriginal) {
this.closeEditor(revertOriginal);
};
this.getActiveEditor = function () {
return activeEditor;
};
/**
* Prepare text input to be displayed at given grid cell
*/
this.prepareEditor = function () {
if (activeEditor && activeEditor.isWaiting()){
this.closeEditor(false, false, function(dataSaved){
if(dataSaved){
that.prepareEditor();
}
});
return;
}
var row = priv.selStart.row();
var col = priv.selStart.col();
var prop = instance.colToProp(col);
var td = instance.getCell(row, col);
var originalValue = instance.getDataAtCell(row, col);
var cellProperties = instance.getCellMeta(row, col);
var editorClass = instance.getCellEditor(cellProperties);
activeEditor = Handsontable.editors.getEditor(editorClass, instance);
activeEditor.prepare(row, col, prop, td, originalValue, cellProperties);
};
this.isEditorOpened = function () {
return activeEditor.isOpened();
};
this.openEditor = function (initialValue) {
activeEditor.beginEditing(initialValue);
};
this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) {
if (!activeEditor){
if(callback) {
callback(false);
}
}
else {
activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback);
}
};
this.closeEditorAndSaveChanges = function(ctrlDown){
return this.closeEditor(false, ctrlDown);
};
this.closeEditorAndRestoreOriginalValue = function(ctrlDown){
return this.closeEditor(true, ctrlDown);
};
init();
};
})(Handsontable);
/**
* Utility to register renderers and common namespace for keeping reference to all renderers classes
*/
(function (Handsontable) {
'use strict';
var registeredRenderers = {};
Handsontable.renderers = {
/**
* Registers renderer under given name
* @param {String} rendererName
* @param {Function} rendererFunction
*/
registerRenderer: function (rendererName, rendererFunction) {
registeredRenderers[rendererName] = rendererFunction
},
/**
* @param {String|Function} rendererName/rendererFunction
* @returns {Function} rendererFunction
*/
getRenderer: function (rendererName) {
if (typeof rendererName == 'function'){
return rendererName;
}
if (typeof rendererName != 'string'){
throw Error('Only strings and functions can be passed as "renderer" parameter ');
}
if (!(rendererName in registeredRenderers)) {
throw Error('No editor registered under name "' + rendererName + '"');
}
return registeredRenderers[rendererName];
}
};
})(Handsontable);
/**
* DOM helper optimized for maximum performance
* It is recommended for Handsontable plugins and renderers, because it is much faster than jQuery
* @type {WalkonableDom}
*/
Handsontable.Dom = new WalkontableDom();
/**
* Returns true if keyCode represents a printable character
* @param {Number} keyCode
* @return {Boolean}
*/
Handsontable.helper.isPrintableChar = function (keyCode) {
return ((keyCode == 32) || //space
(keyCode >= 48 && keyCode <= 57) || //0-9
(keyCode >= 96 && keyCode <= 111) || //numpad
(keyCode >= 186 && keyCode <= 192) || //;=,-./`
(keyCode >= 219 && keyCode <= 222) || //[]{}\|"'
keyCode >= 226 || //special chars (229 for Asian chars)
(keyCode >= 65 && keyCode <= 90)); //a-z
};
Handsontable.helper.isMetaKey = function (keyCode) {
var keyCodes = Handsontable.helper.keyCode;
var metaKeys = [
keyCodes.ARROW_DOWN,
keyCodes.ARROW_UP,
keyCodes.ARROW_LEFT,
keyCodes.ARROW_RIGHT,
keyCodes.HOME,
keyCodes.END,
keyCodes.DELETE,
keyCodes.BACKSPACE,
keyCodes.F1,
keyCodes.F2,
keyCodes.F3,
keyCodes.F4,
keyCodes.F5,
keyCodes.F6,
keyCodes.F7,
keyCodes.F8,
keyCodes.F9,
keyCodes.F10,
keyCodes.F11,
keyCodes.F12,
keyCodes.TAB,
keyCodes.PAGE_DOWN,
keyCodes.PAGE_UP,
keyCodes.ENTER,
keyCodes.ESCAPE,
keyCodes.SHIFT,
keyCodes.CAPS_LOCK,
keyCodes.ALT
];
return metaKeys.indexOf(keyCode) != -1;
};
Handsontable.helper.isCtrlKey = function (keyCode) {
var keys = Handsontable.helper.keyCode;
return [keys.CONTROL_LEFT, 224, keys.COMMAND_LEFT, keys.COMMAND_RIGHT].indexOf(keyCode) != -1;
};
/**
* Converts a value to string
* @param value
* @return {String}
*/
Handsontable.helper.stringify = function (value) {
switch (typeof value) {
case 'string':
case 'number':
return value + '';
break;
case 'object':
if (value === null) {
return '';
}
else {
return value.toString();
}
break;
case 'undefined':
return '';
break;
default:
return value.toString();
}
};
/**
* Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc
* @param index
* @returns {String}
*/
Handsontable.helper.spreadsheetColumnLabel = function (index) {
var dividend = index + 1;
var columnLabel = '';
var modulo;
while (dividend > 0) {
modulo = (dividend - 1) % 26;
columnLabel = String.fromCharCode(65 + modulo) + columnLabel;
dividend = parseInt((dividend - modulo) / 26, 10);
}
return columnLabel;
};
/**
* Checks if value of n is a numeric one
* http://jsperf.com/isnan-vs-isnumeric/4
* @param n
* @returns {boolean}
*/
Handsontable.helper.isNumeric = function (n) {
var t = typeof n;
return t == 'number' ? !isNaN(n) && isFinite(n) :
t == 'string' ? !n.length ? false :
n.length == 1 ? /\d/.test(n) :
/^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) :
t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false;
};
Handsontable.helper.isArray = function (obj) {
return Object.prototype.toString.call(obj).match(/array/i) !== null;
};
/**
* Checks if child is a descendant of given parent node
* http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another
* @param parent
* @param child
* @returns {boolean}
*/
Handsontable.helper.isDescendant = function (parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
/**
* Generates a random hex string. Used as namespace for Handsontable instance events.
* @return {String} - 16 character random string: "92b1bfc74ec4"
*/
Handsontable.helper.randomString = function () {
return walkontableRandomString();
};
/**
* Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`.
* Creates temporary dummy function to call it as constructor.
* Described in ticket: https://github.com/warpech/jquery-handsontable/pull/516
* @param {Object} Child child class
* @param {Object} Parent parent class
* @return {Object} extended Child
*/
Handsontable.helper.inherit = function (Child, Parent) {
Parent.prototype.constructor = Parent;
Child.prototype = new Parent();
Child.prototype.constructor = Child;
return Child;
};
/**
* Perform shallow extend of a target object with extension's own properties
* @param {Object} target An object that will receive the new properties
* @param {Object} extension An object containing additional properties to merge into the target
*/
Handsontable.helper.extend = function (target, extension) {
for (var i in extension) {
if (extension.hasOwnProperty(i)) {
target[i] = extension[i];
}
}
};
Handsontable.helper.getPrototypeOf = function (obj) {
var prototype;
if(typeof obj.__proto__ == "object"){
prototype = obj.__proto__;
} else {
var oldConstructor,
constructor = obj.constructor;
if (typeof obj.constructor == "function") {
oldConstructor = constructor;
if (delete obj.constructor){
constructor = obj.constructor; // get real constructor
obj.constructor = oldConstructor; // restore constructor
}
}
prototype = constructor ? constructor.prototype : null; // needed for IE
}
return prototype;
};
/**
* Factory for columns constructors.
* @param {Object} GridSettings
* @param {Array} conflictList
* @return {Object} ColumnSettings
*/
Handsontable.helper.columnFactory = function (GridSettings, conflictList) {
function ColumnSettings () {}
Handsontable.helper.inherit(ColumnSettings, GridSettings);
// Clear conflict settings
for (var i = 0, len = conflictList.length; i < len; i++) {
ColumnSettings.prototype[conflictList[i]] = void 0;
}
return ColumnSettings;
};
Handsontable.helper.translateRowsToColumns = function (input) {
var i
, ilen
, j
, jlen
, output = []
, olen = 0;
for (i = 0, ilen = input.length; i < ilen; i++) {
for (j = 0, jlen = input[i].length; j < jlen; j++) {
if (j == olen) {
output.push([]);
olen++;
}
output[j].push(input[i][j])
}
}
return output;
};
Handsontable.helper.to2dArray = function (arr) {
var i = 0
, ilen = arr.length;
while (i < ilen) {
arr[i] = [arr[i]];
i++;
}
};
Handsontable.helper.extendArray = function (arr, extension) {
var i = 0
, ilen = extension.length;
while (i < ilen) {
arr.push(extension[i]);
i++;
}
};
/**
* Determines if the given DOM element is an input field.
* Notice: By 'input' we mean input, textarea and select nodes
* @param element - DOM element
* @returns {boolean}
*/
Handsontable.helper.isInput = function (element) {
var inputs = ['INPUT', 'SELECT', 'TEXTAREA'];
return inputs.indexOf(element.nodeName) > -1;
}
/**
* Determines if the given DOM element is an input field placed OUTSIDE of HOT.
* Notice: By 'input' we mean input, textarea and select nodes
* @param element - DOM element
* @returns {boolean}
*/
Handsontable.helper.isOutsideInput = function (element) {
return Handsontable.helper.isInput(element) && element.className.indexOf('handsontableInput') == -1;
};
Handsontable.helper.keyCode = {
MOUSE_LEFT: 1,
MOUSE_RIGHT: 3,
MOUSE_MIDDLE: 2,
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
END: 35,
ENTER: 13,
ESCAPE: 27,
CONTROL_LEFT: 91,
COMMAND_LEFT: 17,
COMMAND_RIGHT: 93,
ALT: 18,
HOME: 36,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
SPACE: 32,
SHIFT: 16,
CAPS_LOCK: 20,
TAB: 9,
ARROW_RIGHT: 39,
ARROW_LEFT: 37,
ARROW_UP: 38,
ARROW_DOWN: 40,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
A: 65,
X: 88,
C: 67,
V: 86
};
/**
* Determines whether given object is a plain Object.
* Note: String and Array are not plain Objects
* @param {*} obj
* @returns {boolean}
*/
Handsontable.helper.isObject = function (obj) {
return Object.prototype.toString.call(obj) == '[object Object]';
};
/**
* Determines whether given object is an Array.
* Note: String is not an Array
* @param {*} obj
* @returns {boolean}
*/
Handsontable.helper.isArray = function(obj){
return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) == '[object Array]';
};
Handsontable.helper.pivot = function (arr) {
var pivotedArr = [];
if(!arr || arr.length == 0 || !arr[0] || arr[0].length == 0){
return pivotedArr;
}
var rowCount = arr.length;
var colCount = arr[0].length;
for(var i = 0; i < rowCount; i++){
for(var j = 0; j < colCount; j++){
if(!pivotedArr[j]){
pivotedArr[j] = [];
}
pivotedArr[j][i] = arr[i][j];
}
}
return pivotedArr;
};
Handsontable.helper.proxy = function (fun, context) {
return function () {
return fun.apply(context, arguments);
};
};
/**
* Factory that produces a function for searching methods (or any properties) which could be defined directly in
* table configuration or implicitly, within cell type definition.
*
* For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be
* defined implicitly using "type" property.
*
* Methods/properties defined explicitly always takes precedence over those defined through "type".
*
* If the method/property is not found in an object, searching is continued recursively through prototype chain, until
* it reaches the Object.prototype.
*
*
* @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable')
* @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type"
* @returns {Function}
*/
Handsontable.helper.cellMethodLookupFactory = function (methodName, allowUndefined) {
allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined;
return function cellMethodLookup (row, col) {
return (function getMethodFromProperties(properties) {
if (!properties){
return; //method not found
}
else if (properties.hasOwnProperty(methodName) && properties[methodName]) { //check if it is own and is not empty
return properties[methodName]; //method defined directly
} else if (properties.hasOwnProperty('type') && properties.type) { //check if it is own and is not empty
var type;
if(typeof properties.type != 'string' ){
throw new Error('Cell type must be a string ');
}
type = translateTypeNameToObject(properties.type);
if (type.hasOwnProperty(methodName)) {
return type[methodName]; //method defined in type.
} else if (allowUndefined) {
return; //method does not defined in type (eg. validator), returns undefined
}
}
return getMethodFromProperties(Handsontable.helper.getPrototypeOf(properties));
})(typeof row == 'number' ? this.getCellMeta(row, col) : row);
};
function translateTypeNameToObject(typeName) {
var type = Handsontable.cellTypes[typeName];
if(typeof type == 'undefined'){
throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
}
return type;
}
};
Handsontable.SelectionPoint = function () {
this._row = null; //private use intended
this._col = null;
};
Handsontable.SelectionPoint.prototype.exists = function () {
return (this._row !== null);
};
Handsontable.SelectionPoint.prototype.row = function (val) {
if (val !== void 0) {
this._row = val;
}
return this._row;
};
Handsontable.SelectionPoint.prototype.col = function (val) {
if (val !== void 0) {
this._col = val;
}
return this._col;
};
Handsontable.SelectionPoint.prototype.coords = function (coords) {
if (coords !== void 0) {
this._row = coords.row;
this._col = coords.col;
}
return {
row: this._row,
col: this._col
}
};
Handsontable.SelectionPoint.prototype.arr = function (arr) {
if (arr !== void 0) {
this._row = arr[0];
this._col = arr[1];
}
return [this._row, this._col]
};
(function (Handsontable) {
'use strict';
/**
* Utility class that gets and saves data from/to the data source using mapping of columns numbers to object property names
* TODO refactor arguments of methods getRange, getText to be numbers (not objects)
* TODO remove priv, GridSettings from object constructor
*
* @param instance
* @param priv
* @param GridSettings
* @constructor
*/
Handsontable.DataMap = function (instance, priv, GridSettings) {
this.instance = instance;
this.priv = priv;
this.GridSettings = GridSettings;
this.dataSource = this.instance.getSettings().data;
if (this.dataSource[0]) {
this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]);
}
else {
this.duckSchema = {};
}
this.createMap();
this.getVars = {}; //used by modifier
this.setVars = {}; //used by modifier
};
Handsontable.DataMap.prototype.DESTINATION_RENDERER = 1;
Handsontable.DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2;
Handsontable.DataMap.prototype.recursiveDuckSchema = function (obj) {
var schema;
if ($.isPlainObject(obj)) {
schema = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if ($.isPlainObject(obj[i])) {
schema[i] = this.recursiveDuckSchema(obj[i]);
}
else {
schema[i] = null;
}
}
}
}
else {
schema = [];
}
return schema;
};
Handsontable.DataMap.prototype.recursiveDuckColumns = function (schema, lastCol, parent) {
var prop, i;
if (typeof lastCol === 'undefined') {
lastCol = 0;
parent = '';
}
if ($.isPlainObject(schema)) {
for (i in schema) {
if (schema.hasOwnProperty(i)) {
if (schema[i] === null) {
prop = parent + i;
this.colToPropCache.push(prop);
this.propToColCache[prop] = lastCol;
lastCol++;
}
else {
lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.');
}
}
}
}
return lastCol;
};
Handsontable.DataMap.prototype.createMap = function () {
if (typeof this.getSchema() === "undefined") {
throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`");
}
var i, ilen, schema = this.getSchema();
this.colToPropCache = [];
this.propToColCache = {};
var columns = this.instance.getSettings().columns;
if (columns) {
for (i = 0, ilen = columns.length; i < ilen; i++) {
this.colToPropCache[i] = columns[i].data;
this.propToColCache[columns[i].data] = i;
}
}
else {
this.recursiveDuckColumns(schema);
}
};
Handsontable.DataMap.prototype.colToProp = function (col) {
col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col);
if (this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') {
return this.colToPropCache[col];
}
else {
return col;
}
};
Handsontable.DataMap.prototype.propToCol = function (prop) {
var col;
if (typeof this.propToColCache[prop] !== 'undefined') {
col = this.propToColCache[prop];
}
else {
col = prop;
}
col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col);
return col;
};
Handsontable.DataMap.prototype.getSchema = function () {
var schema = this.instance.getSettings().dataSchema;
if (schema) {
if (typeof schema === 'function') {
return schema();
}
return schema;
}
return this.duckSchema;
};
/**
* Creates row at the bottom of the data array
* @param {Number} [index] Optional. Index of the row before which the new row will be inserted
*/
Handsontable.DataMap.prototype.createRow = function (index, amount, createdAutomatically) {
var row
, colCount = this.instance.countCols()
, numberOfCreatedRows = 0
, currentIndex;
if (!amount) {
amount = 1;
}
if (typeof index !== 'number' || index >= this.instance.countRows()) {
index = this.instance.countRows();
}
currentIndex = index;
var maxRows = this.instance.getSettings().maxRows;
while (numberOfCreatedRows < amount && this.instance.countRows() < maxRows) {
if (this.instance.dataType === 'array') {
row = [];
for (var c = 0; c < colCount; c++) {
row.push(null);
}
}
else if (this.instance.dataType === 'function') {
row = this.instance.getSettings().dataSchema(index);
}
else {
row = $.extend(true, {}, this.getSchema());
}
if (index === this.instance.countRows()) {
this.dataSource.push(row);
}
else {
this.dataSource.splice(index, 0, row);
}
numberOfCreatedRows++;
currentIndex++;
}
this.instance.PluginHooks.run('afterCreateRow', index, numberOfCreatedRows, createdAutomatically);
this.instance.forceFullRender = true; //used when data was changed
return numberOfCreatedRows;
};
/**
* Creates col at the right of the data array
* @param {Number} [index] Optional. Index of the column before which the new column will be inserted
* * @param {Number} [amount] Optional.
*/
Handsontable.DataMap.prototype.createCol = function (index, amount, createdAutomatically) {
if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
throw new Error("Cannot create new column. When data source in an object, " +
"you can only have as much columns as defined in first data row, data schema or in the 'columns' setting." +
"If you want to be able to add new columns, you have to use array datasource.");
}
var rlen = this.instance.countRows()
, data = this.dataSource
, constructor
, numberOfCreatedCols = 0
, currentIndex;
if (!amount) {
amount = 1;
}
currentIndex = index;
var maxCols = this.instance.getSettings().maxCols;
while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) {
constructor = Handsontable.helper.columnFactory(this.GridSettings, this.priv.columnsSettingConflicts);
if (typeof index !== 'number' || index >= this.instance.countCols()) {
for (var r = 0; r < rlen; r++) {
if (typeof data[r] === 'undefined') {
data[r] = [];
}
data[r].push(null);
}
// Add new column constructor
this.priv.columnSettings.push(constructor);
}
else {
for (var r = 0; r < rlen; r++) {
data[r].splice(currentIndex, 0, null);
}
// Add new column constructor at given index
this.priv.columnSettings.splice(currentIndex, 0, constructor);
}
numberOfCreatedCols++;
currentIndex++;
}
this.instance.PluginHooks.run('afterCreateCol', index, numberOfCreatedCols, createdAutomatically);
this.instance.forceFullRender = true; //used when data was changed
return numberOfCreatedCols;
};
/**
* Removes row from the data array
* @param {Number} [index] Optional. Index of the row to be removed. If not provided, the last row will be removed
* @param {Number} [amount] Optional. Amount of the rows to be removed. If not provided, one row will be removed
*/
Handsontable.DataMap.prototype.removeRow = function (index, amount) {
if (!amount) {
amount = 1;
}
if (typeof index !== 'number') {
index = -amount;
}
index = (this.instance.countRows() + index) % this.instance.countRows();
// We have to map the physical row ids to logical and than perform removing with (possibly) new row id
var logicRows = this.physicalRowsToLogical(index, amount);
var actionWasNotCancelled = this.instance.PluginHooks.execute('beforeRemoveRow', index, amount);
if (actionWasNotCancelled === false) {
return;
}
var data = this.dataSource;
var newData = data.filter(function (row, index) {
return logicRows.indexOf(index) == -1;
});
data.length = 0;
Array.prototype.push.apply(data, newData);
this.instance.PluginHooks.run('afterRemoveRow', index, amount);
this.instance.forceFullRender = true; //used when data was changed
};
/**
* Removes column from the data array
* @param {Number} [index] Optional. Index of the column to be removed. If not provided, the last column will be removed
* @param {Number} [amount] Optional. Amount of the columns to be removed. If not provided, one column will be removed
*/
Handsontable.DataMap.prototype.removeCol = function (index, amount) {
if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
throw new Error("cannot remove column with object data source or columns option specified");
}
if (!amount) {
amount = 1;
}
if (typeof index !== 'number') {
index = -amount;
}
index = (this.instance.countCols() + index) % this.instance.countCols();
var actionWasNotCancelled = this.instance.PluginHooks.execute('beforeRemoveCol', index, amount);
if (actionWasNotCancelled === false) {
return;
}
var data = this.dataSource;
for (var r = 0, rlen = this.instance.countRows(); r < rlen; r++) {
data[r].splice(index, amount);
}
this.priv.columnSettings.splice(index, amount);
this.instance.PluginHooks.run('afterRemoveCol', index, amount);
this.instance.forceFullRender = true; //used when data was changed
};
/**
* Add / removes data from the column
* @param {Number} col Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
Handsontable.DataMap.prototype.spliceCol = function (col, index, amount/*, elements...*/) {
var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
var colData = this.instance.getDataAtCol(col);
var removed = colData.slice(index, index + amount);
var after = colData.slice(index + amount);
Handsontable.helper.extendArray(elements, after);
var i = 0;
while (i < amount) {
elements.push(null); //add null in place of removed elements
i++;
}
Handsontable.helper.to2dArray(elements);
this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol');
return removed;
};
/**
* Add / removes data from the row
* @param {Number} row Index of row in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
Handsontable.DataMap.prototype.spliceRow = function (row, index, amount/*, elements...*/) {
var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
var rowData = this.instance.getDataAtRow(row);
var removed = rowData.slice(index, index + amount);
var after = rowData.slice(index + amount);
Handsontable.helper.extendArray(elements, after);
var i = 0;
while (i < amount) {
elements.push(null); //add null in place of removed elements
i++;
}
this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow');
return removed;
};
/**
* Returns single value from the data array
* @param {Number} row
* @param {Number} prop
*/
Handsontable.DataMap.prototype.get = function (row, prop) {
this.getVars.row = row;
this.getVars.prop = prop;
this.instance.PluginHooks.run('beforeGet', this.getVars);
if (typeof this.getVars.prop === 'string' && this.getVars.prop.indexOf('.') > -1) {
var sliced = this.getVars.prop.split(".");
var out = this.dataSource[this.getVars.row];
if (!out) {
return null;
}
for (var i = 0, ilen = sliced.length; i < ilen; i++) {
out = out[sliced[i]];
if (typeof out === 'undefined') {
return null;
}
}
return out;
}
else if (typeof this.getVars.prop === 'function') {
/**
* allows for interacting with complex structures, for example
* d3/jQuery getter/setter properties:
*
* {columns: [{
* data: function(row, value){
* if(arguments.length === 1){
* return row.property();
* }
* row.property(value);
* }
* }]}
*/
return this.getVars.prop(this.dataSource.slice(
this.getVars.row,
this.getVars.row + 1
)[0]);
}
else {
return this.dataSource[this.getVars.row] ? this.dataSource[this.getVars.row][this.getVars.prop] : null;
}
};
var copyableLookup = Handsontable.helper.cellMethodLookupFactory('copyable', false);
/**
* Returns single value from the data array (intended for clipboard copy to an external application)
* @param {Number} row
* @param {Number} prop
* @return {String}
*/
Handsontable.DataMap.prototype.getCopyable = function (row, prop) {
if (copyableLookup.call(this.instance, row, this.propToCol(prop))) {
return this.get(row, prop);
}
return '';
};
/**
* Saves single value to the data array
* @param {Number} row
* @param {Number} prop
* @param {String} value
* @param {String} [source] Optional. Source of hook runner.
*/
Handsontable.DataMap.prototype.set = function (row, prop, value, source) {
this.setVars.row = row;
this.setVars.prop = prop;
this.setVars.value = value;
this.instance.PluginHooks.run('beforeSet', this.setVars, source || "datamapGet");
if (typeof this.setVars.prop === 'string' && this.setVars.prop.indexOf('.') > -1) {
var sliced = this.setVars.prop.split(".");
var out = this.dataSource[this.setVars.row];
for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) {
out = out[sliced[i]];
}
out[sliced[i]] = this.setVars.value;
}
else if (typeof this.setVars.prop === 'function') {
/* see the `function` handler in `get` */
this.setVars.prop(this.dataSource.slice(
this.setVars.row,
this.setVars.row + 1
)[0], this.setVars.value);
}
else {
this.dataSource[this.setVars.row][this.setVars.prop] = this.setVars.value;
}
};
/**
* This ridiculous piece of code maps rows Id that are present in table data to those displayed for user.
* The trick is, the physical row id (stored in settings.data) is not necessary the same
* as the logical (displayed) row id (e.g. when sorting is applied).
*/
Handsontable.DataMap.prototype.physicalRowsToLogical = function (index, amount) {
var totalRows = this.instance.countRows();
var physicRow = (totalRows + index) % totalRows;
var logicRows = [];
var rowsToRemove = amount;
while (physicRow < totalRows && rowsToRemove) {
this.get(physicRow, 0); //this performs an actual mapping and saves the result to getVars
logicRows.push(this.getVars.row);
rowsToRemove--;
physicRow++;
}
return logicRows;
};
/**
* Clears the data array
*/
Handsontable.DataMap.prototype.clear = function () {
for (var r = 0; r < this.instance.countRows(); r++) {
for (var c = 0; c < this.instance.countCols(); c++) {
this.set(r, this.colToProp(c), '');
}
}
};
/**
* Returns the data array
* @return {Array}
*/
Handsontable.DataMap.prototype.getAll = function () {
return this.dataSource;
};
/**
* Returns data range as array
* @param {Object} start Start selection position
* @param {Object} end End selection position
* @param {Number} destination Destination of datamap.get
* @return {Array}
*/
Handsontable.DataMap.prototype.getRange = function (start, end, destination) {
var r, rlen, c, clen, output = [], row;
var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get;
rlen = Math.max(start.row, end.row);
clen = Math.max(start.col, end.col);
for (r = Math.min(start.row, end.row); r <= rlen; r++) {
row = [];
for (c = Math.min(start.col, end.col); c <= clen; c++) {
row.push(getFn.call(this, r, this.colToProp(c)));
}
output.push(row);
}
return output;
};
/**
* Return data as text (tab separated columns)
* @param {Object} start (Optional) Start selection position
* @param {Object} end (Optional) End selection position
* @return {String}
*/
Handsontable.DataMap.prototype.getText = function (start, end) {
return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_RENDERER));
};
/**
* Return data as copyable text (tab separated columns intended for clipboard copy to an external application)
* @param {Object} start (Optional) Start selection position
* @param {Object} end (Optional) End selection position
* @return {String}
*/
Handsontable.DataMap.prototype.getCopyableText = function (start, end) {
return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR));
};
})(Handsontable);
(function (Handsontable) {
'use strict';
/*
Adds appropriate CSS class to table cell, based on cellProperties
*/
Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
if (cellProperties.readOnly) {
instance.view.wt.wtDom.addClass(TD, cellProperties.readOnlyCellClassName);
}
if (cellProperties.valid === false && cellProperties.invalidCellClassName) {
instance.view.wt.wtDom.addClass(TD, cellProperties.invalidCellClassName);
}
if (!value && cellProperties.placeholder) {
instance.view.wt.wtDom.addClass(TD, cellProperties.placeholderCellClassName);
}
}
})(Handsontable);
/**
* Default text renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var TextRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
Handsontable.renderers.cellDecorator.apply(this, arguments);
if (!value && cellProperties.placeholder) {
value = cellProperties.placeholder;
}
var escaped = Handsontable.helper.stringify(value);
if (cellProperties.rendererTemplate) {
instance.view.wt.wtDom.empty(TD);
var TEMPLATE = document.createElement('TEMPLATE');
TEMPLATE.setAttribute('bind', '{{}}');
TEMPLATE.innerHTML = cellProperties.rendererTemplate;
HTMLTemplateElement.decorate(TEMPLATE);
TEMPLATE.model = instance.getDataAtRow(row);
TD.appendChild(TEMPLATE);
}
else {
instance.view.wt.wtDom.fastInnerText(TD, escaped); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
};
//Handsontable.TextRenderer = TextRenderer; //Left for backward compatibility
Handsontable.renderers.TextRenderer = TextRenderer;
Handsontable.renderers.registerRenderer('text', TextRenderer);
})(Handsontable);
(function (Handsontable) {
var clonableWRAPPER = document.createElement('DIV');
clonableWRAPPER.className = 'htAutocompleteWrapper';
var clonableARROW = document.createElement('DIV');
clonableARROW.className = 'htAutocompleteArrow';
clonableARROW.appendChild(document.createTextNode('\u25BC'));
//this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
var wrapTdContentWithWrapper = function(TD, WRAPPER){
WRAPPER.innerHTML = TD.innerHTML;
Handsontable.Dom.empty(TD);
TD.appendChild(WRAPPER);
};
/**
* Autocomplete renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
var AutocompleteRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement
var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement
Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
TD.appendChild(ARROW);
Handsontable.Dom.addClass(TD, 'htAutocomplete');
if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed
//otherwise empty fields appear borderless in demo/renderers.html (IE)
TD.appendChild(document.createTextNode('\u00A0')); //\u00A0 equals for a text node
//this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
if (!instance.acArrowListener) {
//not very elegant but easy and fast
instance.acArrowListener = function () {
instance.view.wt.getSetting('onCellDblClick');
};
instance.rootElement.on('mousedown', '.htAutocompleteArrow', instance.acArrowListener); //this way we don't bind event listener to each arrow. We rely on propagation instead
}
};
Handsontable.AutocompleteRenderer = AutocompleteRenderer;
Handsontable.renderers.AutocompleteRenderer = AutocompleteRenderer;
Handsontable.renderers.registerRenderer('autocomplete', AutocompleteRenderer);
})(Handsontable);
/**
* Checkbox renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var clonableINPUT = document.createElement('INPUT');
clonableINPUT.className = 'htCheckboxRendererInput';
clonableINPUT.type = 'checkbox';
clonableINPUT.setAttribute('autocomplete', 'off');
var CheckboxRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
if (typeof cellProperties.checkedTemplate === "undefined") {
cellProperties.checkedTemplate = true;
}
if (typeof cellProperties.uncheckedTemplate === "undefined") {
cellProperties.uncheckedTemplate = false;
}
instance.view.wt.wtDom.empty(TD); //TODO identify under what circumstances this line can be removed
var INPUT = clonableINPUT.cloneNode(false); //this is faster than createElement
if (value === cellProperties.checkedTemplate || value === Handsontable.helper.stringify(cellProperties.checkedTemplate)) {
INPUT.checked = true;
TD.appendChild(INPUT);
}
else if (value === cellProperties.uncheckedTemplate || value === Handsontable.helper.stringify(cellProperties.uncheckedTemplate)) {
TD.appendChild(INPUT);
}
else if (value === null) { //default value
INPUT.className += ' noValue';
TD.appendChild(INPUT);
}
else {
instance.view.wt.wtDom.fastInnerText(TD, '#bad value#'); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
var $input = $(INPUT);
if (cellProperties.readOnly) {
$input.on('click', function (event) {
event.preventDefault();
});
}
else {
$input.on('mousedown', function (event) {
event.stopPropagation(); //otherwise can confuse cell mousedown handler
});
$input.on('mouseup', function (event) {
event.stopPropagation(); //otherwise can confuse cell dblclick handler
});
$input.on('change', function(){
if (this.checked) {
instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate);
}
else {
instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate);
}
});
}
if(!instance.CheckboxRenderer || !instance.CheckboxRenderer.beforeKeyDownHookBound){
instance.CheckboxRenderer = {
beforeKeyDownHookBound : true
};
instance.addHook('beforeKeyDown', function(event){
if(event.keyCode == Handsontable.helper.keyCode.SPACE){
var selection = instance.getSelected();
var cell, checkbox, cellProperties;
var selStart = {
row: Math.min(selection[0], selection[2]),
col: Math.min(selection[1], selection[3])
};
var selEnd = {
row: Math.max(selection[0], selection[2]),
col: Math.max(selection[1], selection[3])
};
for(var row = selStart.row; row <= selEnd.row; row++ ){
for(var col = selEnd.col; col <= selEnd.col; col++){
cell = instance.getCell(row, col);
cellProperties = instance.getCellMeta(row, col);
checkbox = cell.querySelectorAll('input[type=checkbox]');
if(checkbox.length > 0 && !cellProperties.readOnly){
if(!event.isImmediatePropagationStopped()){
event.stopImmediatePropagation();
event.preventDefault();
}
for(var i = 0, len = checkbox.length; i < len; i++){
checkbox[i].checked = !checkbox[i].checked;
$(checkbox[i]).trigger('change');
}
}
}
}
}
});
}
};
Handsontable.CheckboxRenderer = CheckboxRenderer;
Handsontable.renderers.CheckboxRenderer = CheckboxRenderer;
Handsontable.renderers.registerRenderer('checkbox', CheckboxRenderer);
})(Handsontable);
/**
* Numeric cell renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var NumericRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
if (Handsontable.helper.isNumeric(value)) {
if (typeof cellProperties.language !== 'undefined') {
numeral.language(cellProperties.language)
}
value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/
instance.view.wt.wtDom.addClass(TD, 'htNumeric');
}
Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
};
Handsontable.NumericRenderer = NumericRenderer; //Left for backward compatibility with versions prior 0.10.0
Handsontable.renderers.NumericRenderer = NumericRenderer;
Handsontable.renderers.registerRenderer('numeric', NumericRenderer);
})(Handsontable);
(function(Handosntable){
'use strict';
var PasswordRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
value = TD.innerHTML;
var hash;
var hashLength = cellProperties.hashLength || value.length;
var hashSymbol = cellProperties.hashSymbol || '*';
for( hash = ''; hash.split(hashSymbol).length - 1 < hashLength; hash += hashSymbol);
instance.view.wt.wtDom.fastInnerHTML(TD, hash);
};
Handosntable.PasswordRenderer = PasswordRenderer;
Handosntable.renderers.PasswordRenderer = PasswordRenderer;
Handosntable.renderers.registerRenderer('password', PasswordRenderer);
})(Handsontable);
(function (Handsontable) {
function HtmlRenderer(instance, TD, row, col, prop, value, cellProperties){
Handsontable.renderers.cellDecorator.apply(this, arguments);
Handsontable.Dom.fastInnerHTML(TD, value);
}
Handsontable.renderers.registerRenderer('html', HtmlRenderer);
Handsontable.renderers.HtmlRenderer = HtmlRenderer;
})(Handsontable);
(function (Handsontable) {
'use strict';
Handsontable.EditorState = {
VIRGIN: 'STATE_VIRGIN', //before editing
EDITING: 'STATE_EDITING',
WAITING: 'STATE_WAITING', //waiting for async validation
FINISHED: 'STATE_FINISHED'
};
function BaseEditor(instance) {
this.instance = instance;
this.state = Handsontable.EditorState.VIRGIN;
this._opened = false;
this._closeCallback = null;
this.init();
}
BaseEditor.prototype._fireCallbacks = function(result) {
if(this._closeCallback){
this._closeCallback(result);
this._closeCallback = null;
}
}
BaseEditor.prototype.init = function(){};
BaseEditor.prototype.getValue = function(){
throw Error('Editor getValue() method unimplemented');
};
BaseEditor.prototype.setValue = function(newValue){
throw Error('Editor setValue() method unimplemented');
};
BaseEditor.prototype.open = function(){
throw Error('Editor open() method unimplemented');
};
BaseEditor.prototype.close = function(){
throw Error('Editor close() method unimplemented');
};
BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties){
this.TD = td;
this.row = row;
this.col = col;
this.prop = prop;
this.originalValue = originalValue;
this.cellProperties = cellProperties;
this.state = Handsontable.EditorState.VIRGIN;
};
BaseEditor.prototype.extend = function(){
var baseClass = this.constructor;
function Editor(){
baseClass.apply(this, arguments);
}
function inherit(Child, Parent){
function Bridge() {
}
Bridge.prototype = Parent.prototype;
Child.prototype = new Bridge();
Child.prototype.constructor = Child;
return Child;
}
return inherit(Editor, baseClass);
};
BaseEditor.prototype.saveValue = function (val, ctrlDown) {
if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)
var sel = this.instance.getSelected();
this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit');
}
else {
this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit');
}
};
BaseEditor.prototype.beginEditing = function(initialValue){
if (this.state != Handsontable.EditorState.VIRGIN) {
return;
}
if (this.cellProperties.readOnly) {
return;
}
this.instance.view.scrollViewport({row: this.row, col: this.col});
this.instance.view.render();
this.state = Handsontable.EditorState.EDITING;
initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue;
this.setValue(Handsontable.helper.stringify(initialValue));
this.open();
this._opened = true;
this.focus();
this.instance.view.render(); //only rerender the selections (FillHandle should disappear when beginediting is triggered)
};
BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) {
if (callback) {
var previousCloseCallback = this._closeCallback;
this._closeCallback = function (result) {
if(previousCloseCallback){
previousCloseCallback(result);
}
callback(result);
};
}
if (this.isWaiting()) {
return;
}
if (this.state == Handsontable.EditorState.VIRGIN) {
var that = this;
setTimeout(function () {
that._fireCallbacks(true);
});
return;
}
if (this.state == Handsontable.EditorState.EDITING) {
if (restoreOriginalValue) {
this.cancelChanges();
return;
}
var val = [
[String.prototype.trim.call(this.getValue())] //String.prototype.trim is defined in Walkontable polyfill.js
];
this.state = Handsontable.EditorState.WAITING;
this.saveValue(val, ctrlDown);
if(this.instance.getCellValidator(this.cellProperties)){
var that = this;
this.instance.addHookOnce('afterValidate', function (result) {
that.state = Handsontable.EditorState.FINISHED;
that.discardEditor(result);
});
} else {
this.state = Handsontable.EditorState.FINISHED;
this.discardEditor(true);
}
}
};
BaseEditor.prototype.cancelChanges = function () {
this.state = Handsontable.EditorState.FINISHED;
this.discardEditor();
};
BaseEditor.prototype.discardEditor = function (result) {
if (this.state !== Handsontable.EditorState.FINISHED) {
return;
}
if (result === false && this.cellProperties.allowInvalid !== true) { //validator was defined and failed
this.instance.selectCell(this.row, this.col);
this.focus();
this.state = Handsontable.EditorState.EDITING;
this._fireCallbacks(false);
}
else {
this.close();
this._opened = false;
this.state = Handsontable.EditorState.VIRGIN;
this._fireCallbacks(true);
}
};
BaseEditor.prototype.isOpened = function(){
return this._opened;
};
BaseEditor.prototype.isWaiting = function () {
return this.state === Handsontable.EditorState.WAITING;
};
Handsontable.editors.BaseEditor = BaseEditor;
})(Handsontable);
(function(Handsontable){
var TextEditor = Handsontable.editors.BaseEditor.prototype.extend();
TextEditor.prototype.init = function(){
this.createElements();
this.bindEvents();
};
TextEditor.prototype.getValue = function(){
return this.TEXTAREA.value
};
TextEditor.prototype.setValue = function(newValue){
this.TEXTAREA.value = newValue;
};
var onBeforeKeyDown = function onBeforeKeyDown(event){
var instance = this;
var that = instance.getActiveEditor();
var keyCodes = Handsontable.helper.keyCode;
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
//Process only events that have been fired in the editor
if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()){
return;
}
if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
//when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea
event.stopImmediatePropagation();
return;
}
switch (event.keyCode) {
case keyCodes.ARROW_RIGHT:
if (that.wtDom.getCaretPosition(that.TEXTAREA) !== that.TEXTAREA.value.length) {
event.stopImmediatePropagation();
}
break;
case keyCodes.ARROW_LEFT: /* arrow left */
if (that.wtDom.getCaretPosition(that.TEXTAREA) !== 0) {
event.stopImmediatePropagation();
}
break;
case keyCodes.ENTER:
var selected = that.instance.getSelected();
var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]);
if ((ctrlDown && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line
if(that.isOpened()){
that.setValue(that.getValue() + '\n');
that.focus();
} else {
that.beginEditing(that.originalValue + '\n')
}
event.stopImmediatePropagation();
}
event.preventDefault(); //don't add newline to field
break;
case keyCodes.A:
case keyCodes.X:
case keyCodes.C:
case keyCodes.V:
if(ctrlDown){
event.stopImmediatePropagation(); //CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context)
break;
}
case keyCodes.BACKSPACE:
case keyCodes.DELETE:
case keyCodes.HOME:
case keyCodes.END:
event.stopImmediatePropagation(); //backspace, delete, home, end should only work locally when cell is edited (not in table context)
break;
}
};
TextEditor.prototype.open = function(){
this.refreshDimensions(); //need it instantly, to prevent https://github.com/warpech/jquery-handsontable/issues/348
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.close = function(){
this.textareaParentStyle.display = 'none';
if (document.activeElement === this.TEXTAREA) {
this.instance.listen(); //don't refocus the table if user focused some cell outside of HT on purpose
}
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.focus = function(){
this.TEXTAREA.focus();
this.wtDom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length);
};
TextEditor.prototype.createElements = function () {
this.$body = $(document.body);
this.wtDom = new WalkontableDom();
this.TEXTAREA = document.createElement('TEXTAREA');
this.$textarea = $(this.TEXTAREA);
this.wtDom.addClass(this.TEXTAREA, 'handsontableInput');
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.TEXTAREA_PARENT = document.createElement('DIV');
this.wtDom.addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder');
this.textareaParentStyle = this.TEXTAREA_PARENT.style;
this.textareaParentStyle.top = 0;
this.textareaParentStyle.left = 0;
this.textareaParentStyle.display = 'none';
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
this.instance.rootElement[0].appendChild(this.TEXTAREA_PARENT);
var that = this;
Handsontable.PluginHooks.add('afterRender', function () {
that.instance.registerTimeout('refresh_editor_dimensions', function () {
that.refreshDimensions();
}, 0);
});
};
TextEditor.prototype.refreshDimensions = function () {
if (this.state !== Handsontable.EditorState.EDITING) {
return;
}
///start prepare textarea position
this.TD = this.instance.getCell(this.row, this.col);
if (!this.TD) {
//TD is outside of the viewport. Otherwise throws exception when scrolling the table while a cell is edited
return;
}
var $td = $(this.TD); //because old td may have been scrolled out with scrollViewport
var currentOffset = this.wtDom.offset(this.TD);
var containerOffset = this.wtDom.offset(this.instance.rootElement[0]);
var scrollTop = this.instance.rootElement.scrollTop();
var scrollLeft = this.instance.rootElement.scrollLeft();
var editTop = currentOffset.top - containerOffset.top + scrollTop - 1;
var editLeft = currentOffset.left - containerOffset.left + scrollLeft - 1;
var settings = this.instance.getSettings();
var rowHeadersCount = settings.rowHeaders === false ? 0 : 1;
var colHeadersCount = settings.colHeaders === false ? 0 : 1;
if (editTop < 0) {
editTop = 0;
}
if (editLeft < 0) {
editLeft = 0;
}
if (rowHeadersCount > 0 && parseInt($td.css('border-top-width'), 10) > 0) {
editTop += 1;
}
if (colHeadersCount > 0 && parseInt($td.css('border-left-width'), 10) > 0) {
editLeft += 1;
}
this.textareaParentStyle.top = editTop + 'px';
this.textareaParentStyle.left = editLeft + 'px';
///end prepare textarea position
var width = $td.width()
, maxWidth = this.instance.view.maximumVisibleElementWidth(editLeft) - 10 //10 is TEXTAREAs border and padding
, height = $td.outerHeight() - 4
, maxHeight = this.instance.view.maximumVisibleElementHeight(editTop) - 5; //10 is TEXTAREAs border and padding
if (parseInt($td.css('border-top-width'), 10) > 0) {
height -= 1;
}
if (parseInt($td.css('border-left-width'), 10) > 0) {
if (rowHeadersCount > 0) {
width -= 1;
}
}
//in future may change to pure JS http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize
this.$textarea.autoResize({
minHeight: Math.min(height, maxHeight),
maxHeight: maxHeight, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
minWidth: Math.min(width, maxWidth),
maxWidth: maxWidth, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
animate: false,
extraSpace: 0
});
this.textareaParentStyle.display = 'block';
};
TextEditor.prototype.bindEvents = function () {
this.$textarea.on('cut.editor', function (event) {
event.stopPropagation();
});
this.$textarea.on('paste.editor', function (event) {
event.stopPropagation();
});
};
Handsontable.editors.TextEditor = TextEditor;
Handsontable.editors.registerEditor('text', Handsontable.editors.TextEditor);
})(Handsontable);
(function(Handsontable){
//Blank editor, because all the work is done by renderer
var CheckboxEditor = Handsontable.editors.BaseEditor.prototype.extend();
CheckboxEditor.prototype.beginEditing = function () {
this.saveValue([
[!this.originalValue]
]);
};
CheckboxEditor.prototype.finishEditing = function () {};
CheckboxEditor.prototype.init = function () {};
CheckboxEditor.prototype.open = function () {};
CheckboxEditor.prototype.close = function () {};
CheckboxEditor.prototype.getValue = function () {};
CheckboxEditor.prototype.setValue = function () {};
CheckboxEditor.prototype.focus = function () {};
Handsontable.editors.CheckboxEditor = CheckboxEditor;
Handsontable.editors.registerEditor('checkbox', CheckboxEditor);
})(Handsontable);
(function (Handsontable) {
var DateEditor = Handsontable.editors.TextEditor.prototype.extend();
DateEditor.prototype.init = function () {
if (!$.datepicker) {
throw new Error("jQuery UI Datepicker dependency not found. Did you forget to include jquery-ui.custom.js or its substitute?");
}
Handsontable.editors.TextEditor.prototype.init.apply(this, arguments);
this.isCellEdited = false;
var that = this;
this.instance.addHook('afterDestroy', function () {
that.destroyElements();
})
};
DateEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
this.datePicker = document.createElement('DIV');
this.instance.view.wt.wtDom.addClass(this.datePicker, 'htDatepickerHolder');
this.datePickerStyle = this.datePicker.style;
this.datePickerStyle.position = 'absolute';
this.datePickerStyle.top = 0;
this.datePickerStyle.left = 0;
this.datePickerStyle.zIndex = 99;
document.body.appendChild(this.datePicker);
this.$datePicker = $(this.datePicker);
var that = this;
var defaultOptions = {
dateFormat: "yy-mm-dd",
showButtonPanel: true,
changeMonth: true,
changeYear: true,
onSelect: function (dateStr) {
that.setValue(dateStr);
that.finishEditing(false);
}
};
this.$datePicker.datepicker(defaultOptions);
/**
* Prevent recognizing clicking on jQuery Datepicker as clicking outside of table
*/
this.$datePicker.on('mousedown', function (event) {
event.stopPropagation();
});
this.hideDatepicker();
};
DateEditor.prototype.destroyElements = function () {
this.$datePicker.datepicker('destroy');
this.$datePicker.remove();
};
DateEditor.prototype.beginEditing = function (row, col, prop, useOriginalValue, suffix) {
Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments);
this.showDatepicker();
};
DateEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
this.hideDatepicker();
Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);
};
DateEditor.prototype.showDatepicker = function () {
var $td = $(this.TD);
var offset = $td.offset();
this.datePickerStyle.top = (offset.top + $td.height()) + 'px';
this.datePickerStyle.left = offset.left + 'px';
var dateOptions = {
defaultDate: this.originalValue || void 0
};
$.extend(dateOptions, this.cellProperties);
this.$datePicker.datepicker("option", dateOptions);
if (this.originalValue) {
this.$datePicker.datepicker("setDate", this.originalValue);
}
this.datePickerStyle.display = 'block';
};
DateEditor.prototype.hideDatepicker = function () {
this.datePickerStyle.display = 'none';
};
Handsontable.editors.DateEditor = DateEditor;
Handsontable.editors.registerEditor('date', DateEditor);
})(Handsontable);
/**
* This is inception. Using Handsontable as Handsontable editor
*/
(function (Handsontable) {
"use strict";
var HandsontableEditor = Handsontable.editors.TextEditor.prototype.extend();
HandsontableEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
var DIV = document.createElement('DIV');
DIV.className = 'handsontableEditor';
this.TEXTAREA_PARENT.appendChild(DIV);
this.$htContainer = $(DIV);
this.$htContainer.handsontable();
};
HandsontableEditor.prototype.prepare = function (td, row, col, prop, value, cellProperties) {
Handsontable.editors.TextEditor.prototype.prepare.apply(this, arguments);
var parent = this;
var options = {
startRows: 0,
startCols: 0,
minRows: 0,
minCols: 0,
className: 'listbox',
copyPaste: false,
cells: function () {
return {
readOnly: true
}
},
fillHandle: false,
afterOnCellMouseDown: function () {
var value = this.getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
parent.setValue(value);
}
parent.instance.destroyEditor();
},
beforeOnKeyDown: function (event) {
var instance = this;
switch (event.keyCode) {
case Handsontable.helper.keyCode.ESCAPE:
parent.instance.destroyEditor(true);
event.stopImmediatePropagation();
event.preventDefault();
break;
case Handsontable.helper.keyCode.ENTER: //enter
var sel = instance.getSelected();
var value = this.getDataAtCell(sel[0], sel[1]);
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
parent.setValue(value);
}
parent.instance.destroyEditor();
break;
case Handsontable.helper.keyCode.ARROW_UP:
if (instance.getSelected() && instance.getSelected()[0] == 0 && !parent.cellProperties.strict){
instance.deselectCell();
parent.instance.listen();
parent.focus();
event.preventDefault();
event.stopImmediatePropagation();
}
break;
}
}
};
if (this.cellProperties.handsontable) {
options = $.extend(options, cellProperties.handsontable);
}
this.$htContainer.handsontable('destroy');
this.$htContainer.handsontable(options);
};
var onBeforeKeyDown = function (event) {
if (event.isImmediatePropagationStopped()) {
return;
}
var editor = this.getActiveEditor();
var innerHOT = editor.$htContainer.handsontable('getInstance');
if (event.keyCode == Handsontable.helper.keyCode.ARROW_DOWN) {
if (!innerHOT.getSelected()){
innerHOT.selectCell(0, 0);
} else {
var selectedRow = innerHOT.getSelected()[0];
var rowToSelect = selectedRow < innerHOT.countRows() - 1 ? selectedRow + 1 : selectedRow;
innerHOT.selectCell(rowToSelect, 0);
}
event.preventDefault();
event.stopImmediatePropagation();
}
};
HandsontableEditor.prototype.open = function () {
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
Handsontable.editors.TextEditor.prototype.open.apply(this, arguments);
this.$htContainer.handsontable('render');
if (this.cellProperties.strict) {
this.$htContainer.handsontable('selectCell', 0, 0);
this.$textarea[0].style.visibility = 'hidden';
} else {
this.$htContainer.handsontable('deselectCell');
this.$textarea[0].style.visibility = 'visible';
}
this.wtDom.setCaretPosition(this.$textarea[0], 0, this.$textarea[0].value.length);
};
HandsontableEditor.prototype.close = function () {
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
this.instance.listen();
Handsontable.editors.TextEditor.prototype.close.apply(this, arguments);
};
HandsontableEditor.prototype.focus = function () {
this.instance.listen();
Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments);
};
HandsontableEditor.prototype.beginEditing = function (initialValue) {
var onBeginEditing = this.instance.getSettings().onBeginEditing;
if (onBeginEditing && onBeginEditing() === false) {
return;
}
Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments);
};
HandsontableEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
if (this.$htContainer.handsontable('isListening')) { //if focus is still in the HOT editor
this.instance.listen(); //return the focus to the parent HOT instance
}
if (this.$htContainer.handsontable('getSelected')) {
var value = this.$htContainer.handsontable('getInstance').getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
this.setValue(value);
}
}
return Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);
};
Handsontable.editors.HandsontableEditor = HandsontableEditor;
Handsontable.editors.registerEditor('handsontable', HandsontableEditor);
})(Handsontable);
(function (Handsontable) {
var AutocompleteEditor = Handsontable.editors.HandsontableEditor.prototype.extend();
AutocompleteEditor.prototype.init = function () {
Handsontable.editors.HandsontableEditor.prototype.init.apply(this, arguments);
this.query = null;
};
AutocompleteEditor.prototype.createElements = function(){
Handsontable.editors.HandsontableEditor.prototype.createElements.apply(this, arguments);
this.$htContainer.addClass('autocompleteEditor');
};
AutocompleteEditor.prototype.bindEvents = function(){
var that = this;
this.$textarea.on('keydown.autocompleteEditor', function(event){
if(!Handsontable.helper.isMetaKey(event.keyCode) || [Handsontable.helper.keyCode.BACKSPACE, Handsontable.helper.keyCode.DELETE].indexOf(event.keyCode) != -1){
setTimeout(function () {
that.queryChoices(that.$textarea.val());
});
} else if (event.keyCode == Handsontable.helper.keyCode.ENTER && that.cellProperties.strict !== true){
that.$htContainer.handsontable('deselectCell');
}
});
this.$htContainer.on('mouseenter', function () {
that.$htContainer.handsontable('deselectCell');
});
this.$htContainer.on('mouseleave', function () {
that.queryChoices(that.query);
});
Handsontable.editors.HandsontableEditor.prototype.bindEvents.apply(this, arguments);
};
AutocompleteEditor.prototype.beginEditing = function () {
Handsontable.editors.HandsontableEditor.prototype.beginEditing.apply(this, arguments);
var that = this;
setTimeout(function () {
that.queryChoices(that.TEXTAREA.value);
});
var hot = this.$htContainer.handsontable('getInstance');
hot.updateSettings({
'colWidths': [this.wtDom.outerWidth(this.TEXTAREA) - 2],
afterRenderer: function (TD, row, col, prop, value) {
var caseSensitive = this.getCellMeta(row, col).filteringCaseSensitive === true;
var indexOfMatch = caseSensitive ? value.indexOf(that.query) : value.toLowerCase().indexOf(that.query.toLowerCase());
if(indexOfMatch != -1){
var match = value.substr(indexOfMatch, that.query.length);
TD.innerHTML = value.replace(match, '<strong>' + match + '</strong>');
}
}
});
};
var onBeforeKeyDownInner;
AutocompleteEditor.prototype.open = function () {
var parent = this;
onBeforeKeyDownInner = function (event) {
var instance = this;
if (event.keyCode == Handsontable.helper.keyCode.ARROW_UP){
if (instance.getSelected() && instance.getSelected()[0] == 0){
if(!parent.cellProperties.strict){
instance.deselectCell();
}
parent.instance.listen();
parent.focus();
event.preventDefault();
event.stopImmediatePropagation();
}
}
};
this.$htContainer.handsontable('getInstance').addHook('beforeKeyDown', onBeforeKeyDownInner);
Handsontable.editors.HandsontableEditor.prototype.open.apply(this, arguments);
this.$textarea[0].style.visibility = 'visible';
parent.focus();
};
AutocompleteEditor.prototype.close = function () {
this.$htContainer.handsontable('getInstance').removeHook('beforeKeyDown', onBeforeKeyDownInner);
Handsontable.editors.HandsontableEditor.prototype.close.apply(this, arguments);
};
AutocompleteEditor.prototype.queryChoices = function(query){
this.query = query;
if (typeof this.cellProperties.source == 'function'){
var that = this;
this.cellProperties.source(query, function(choices){
that.updateChoicesList(choices)
});
} else if (Handsontable.helper.isArray(this.cellProperties.source)) {
var choices;
if(!query || this.cellProperties.filter === false){
choices = this.cellProperties.source;
} else {
var filteringCaseSensitive = this.cellProperties.filteringCaseSensitive === true;
var lowerCaseQuery = query.toLowerCase();
choices = this.cellProperties.source.filter(function(choice){
if (filteringCaseSensitive) {
return choice.indexOf(query) != -1;
} else {
return choice.toLowerCase().indexOf(lowerCaseQuery) != -1;
}
});
}
this.updateChoicesList(choices)
} else {
this.updateChoicesList([]);
}
};
function findItemIndexToHighlight(items, value){
var bestMatch = {};
var valueLength = value.length;
var currentItem;
var indexOfValue;
var charsLeft;
for(var i = 0, len = items.length; i < len; i++){
currentItem = items[i];
if(valueLength > 0){
indexOfValue = currentItem.indexOf(value)
} else {
indexOfValue = currentItem === value ? 0 : -1;
}
if(indexOfValue == -1) continue;
charsLeft = currentItem.length - indexOfValue - valueLength;
if( typeof bestMatch.indexOfValue == 'undefined'
|| bestMatch.indexOfValue > indexOfValue
|| ( bestMatch.indexOfValue == indexOfValue && bestMatch.charsLeft > charsLeft ) ){
bestMatch.indexOfValue = indexOfValue;
bestMatch.charsLeft = charsLeft;
bestMatch.index = i;
}
}
return bestMatch.index;
}
AutocompleteEditor.prototype.updateChoicesList = function (choices) {
this.$htContainer.handsontable('loadData', Handsontable.helper.pivot([choices]));
var value = this.getValue();
var rowToHighlight;
if(this.cellProperties.strict === true){
rowToHighlight = findItemIndexToHighlight(choices, value);
if ( typeof rowToHighlight == 'undefined' && this.cellProperties.allowInvalid === false){
rowToHighlight = 0;
}
}
if(typeof rowToHighlight == 'undefined'){
this.$htContainer.handsontable('deselectCell');
} else {
this.$htContainer.handsontable('selectCell', rowToHighlight, 0);
}
this.focus();
};
Handsontable.editors.AutocompleteEditor = AutocompleteEditor;
Handsontable.editors.registerEditor('autocomplete', AutocompleteEditor);
})(Handsontable);
(function(Handsontable){
var PasswordEditor = Handsontable.editors.TextEditor.prototype.extend();
var wtDom = new WalkontableDom();
PasswordEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
this.TEXTAREA = document.createElement('input');
this.TEXTAREA.setAttribute('type', 'password');
this.TEXTAREA.className = 'handsontableInput';
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.$textarea = $(this.TEXTAREA);
wtDom.empty(this.TEXTAREA_PARENT);
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
};
Handsontable.editors.PasswordEditor = PasswordEditor;
Handsontable.editors.registerEditor('password', PasswordEditor);
})(Handsontable);
(function (Handsontable) {
var SelectEditor = Handsontable.editors.BaseEditor.prototype.extend();
SelectEditor.prototype.init = function(){
this.select = $('<select />')
.addClass('htSelectEditor')
.hide();
this.instance.rootElement.append(this.select);
};
SelectEditor.prototype.prepare = function(){
Handsontable.editors.BaseEditor.prototype.prepare.apply(this, arguments);
var selectOptions = this.cellProperties.selectOptions;
var options;
if (typeof selectOptions == 'function'){
options = this.prepareOptions(selectOptions(this.row, this.col, this.prop))
} else {
options = this.prepareOptions(selectOptions);
}
var optionElements = [];
for (var option in options){
if (options.hasOwnProperty(option)){
var optionElement = $('<option />');
optionElement.val(option);
optionElement.html(options[option]);
optionElements.push(optionElement);
}
}
this.select.empty();
this.select.append(optionElements);
};
SelectEditor.prototype.prepareOptions = function(optionsToPrepare){
var preparedOptions = {};
if (Handsontable.helper.isArray(optionsToPrepare)){
for(var i = 0, len = optionsToPrepare.length; i < len; i++){
preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i];
}
}
else if (typeof optionsToPrepare == 'object') {
preparedOptions = optionsToPrepare;
}
return preparedOptions;
};
SelectEditor.prototype.getValue = function () {
return this.select.val();
};
SelectEditor.prototype.setValue = function (value) {
this.select.val(value);
};
var onBeforeKeyDown = function (event) {
var instance = this;
var editor = instance.getActiveEditor();
switch (event.keyCode){
case Handsontable.helper.keyCode.ARROW_UP:
var previousOption = editor.select.find('option:selected').prev();
if (previousOption.length == 1){
previousOption.prop('selected', true);
}
event.stopImmediatePropagation();
event.preventDefault();
break;
case Handsontable.helper.keyCode.ARROW_DOWN:
var nextOption = editor.select.find('option:selected').next();
if (nextOption.length == 1){
nextOption.prop('selected', true);
}
event.stopImmediatePropagation();
event.preventDefault();
break;
}
};
SelectEditor.prototype.open = function () {
this.select.css({
height: $(this.TD).height(),
'min-width' : $(this.TD).outerWidth()
});
this.select.show();
this.select.offset($(this.TD).offset());
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
SelectEditor.prototype.close = function () {
this.select.hide();
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
SelectEditor.prototype.focus = function () {
this.select.focus();
};
Handsontable.editors.SelectEditor = SelectEditor;
Handsontable.editors.registerEditor('select', SelectEditor);
})(Handsontable);
(function (Handsontable) {
var DropdownEditor = Handsontable.editors.AutocompleteEditor.prototype.extend();
DropdownEditor.prototype.prepare = function () {
Handsontable.editors.AutocompleteEditor.prototype.prepare.apply(this, arguments);
this.cellProperties.filter = false;
this.cellProperties.strict = true;
};
Handsontable.editors.DropdownEditor = DropdownEditor;
Handsontable.editors.registerEditor('dropdown', DropdownEditor);
})(Handsontable);
/**
* Numeric cell validator
* @param {*} value - Value of edited cell
* @param {*} callback - Callback called with validation result
*/
Handsontable.NumericValidator = function (value, callback) {
if (value === null) {
value = '';
}
callback(/^-?\d*\.?\d*$/.test(value));
};
/**
* Function responsible for validation of autocomplete value
* @param {*} value - Value of edited cell
* @param {*} calback - Callback called with validation result
*/
var process = function (value, callback) {
var originalVal = value;
var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null;
return function (source) {
var found = false;
for (var s = 0, slen = source.length; s < slen; s++) {
if (originalVal === source[s]) {
found = true; //perfect match
break;
}
else if (lowercaseVal === source[s].toLowerCase()) {
// changes[i][3] = source[s]; //good match, fix the case << TODO?
found = true;
break;
}
}
callback(found);
}
};
/**
* Autocomplete cell validator
* @param {*} value - Value of edited cell
* @param {*} calback - Callback called with validation result
*/
Handsontable.AutocompleteValidator = function (value, callback) {
if (this.strict && this.source) {
typeof this.source === 'function' ? this.source(value, process(value, callback)) : process(value, callback)(this.source);
} else {
callback(true);
}
};
/**
* Cell type is just a shortcut for setting bunch of cellProperties (used in getCellMeta)
*/
Handsontable.AutocompleteCell = {
editor: Handsontable.editors.AutocompleteEditor,
renderer: Handsontable.renderers.AutocompleteRenderer,
validator: Handsontable.AutocompleteValidator
};
Handsontable.CheckboxCell = {
editor: Handsontable.editors.CheckboxEditor,
renderer: Handsontable.renderers.CheckboxRenderer
};
Handsontable.TextCell = {
editor: Handsontable.editors.TextEditor,
renderer: Handsontable.renderers.TextRenderer
};
Handsontable.NumericCell = {
editor: Handsontable.editors.TextEditor,
renderer: Handsontable.renderers.NumericRenderer,
validator: Handsontable.NumericValidator,
dataType: 'number'
};
Handsontable.DateCell = {
editor: Handsontable.editors.DateEditor,
renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell
};
Handsontable.HandsontableCell = {
editor: Handsontable.editors.HandsontableEditor,
renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell
};
Handsontable.PasswordCell = {
editor: Handsontable.editors.PasswordEditor,
renderer: Handsontable.renderers.PasswordRenderer,
copyable: false
};
Handsontable.DropdownCell = {
editor: Handsontable.editors.DropdownEditor,
renderer: Handsontable.renderers.AutocompleteRenderer, //displays small gray arrow on right side of the cell
validator: Handsontable.AutocompleteValidator
};
//here setup the friendly aliases that are used by cellProperties.type
Handsontable.cellTypes = {
text: Handsontable.TextCell,
date: Handsontable.DateCell,
numeric: Handsontable.NumericCell,
checkbox: Handsontable.CheckboxCell,
autocomplete: Handsontable.AutocompleteCell,
handsontable: Handsontable.HandsontableCell,
password: Handsontable.PasswordCell,
dropdown: Handsontable.DropdownCell
};
//here setup the friendly aliases that are used by cellProperties.renderer and cellProperties.editor
Handsontable.cellLookup = {
validator: {
numeric: Handsontable.NumericValidator,
autocomplete: Handsontable.AutocompleteValidator
}
};
/*
* jQuery.fn.autoResize 1.1+
* --
* https://github.com/warpech/jQuery.fn.autoResize
*
* This fork differs from others in a way that it autoresizes textarea in 2-dimensions (horizontally and vertically).
* It was originally forked from alexbardas's repo but maybe should be merged with dpashkevich's repo in future.
*
* originally forked from:
* https://github.com/jamespadolsey/jQuery.fn.autoResize
* which is now located here:
* https://github.com/alexbardas/jQuery.fn.autoResize
* though the mostly maintained for is here:
* https://github.com/dpashkevich/jQuery.fn.autoResize/network
*
* --
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
(function($){
autoResize.defaults = {
onResize: function(){},
animate: {
duration: 200,
complete: function(){}
},
extraSpace: 50,
minHeight: 'original',
maxHeight: 500,
minWidth: 'original',
maxWidth: 500
};
autoResize.cloneCSSProperties = [
'lineHeight', 'textDecoration', 'letterSpacing',
'fontSize', 'fontFamily', 'fontStyle', 'fontWeight',
'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust',
'padding'
];
autoResize.cloneCSSValues = {
position: 'absolute',
top: -9999,
left: -9999,
opacity: 0,
overflow: 'hidden',
overflowX: 'hidden',
overflowY: 'hidden',
border: '1px solid black',
padding: '0.49em' //this must be about the width of caps W character
};
autoResize.resizableFilterSelector = 'textarea,input:not(input[type]),input[type=text],input[type=password]';
autoResize.AutoResizer = AutoResizer;
$.fn.autoResize = autoResize;
function autoResize(config) {
this.filter(autoResize.resizableFilterSelector).each(function(){
new AutoResizer( $(this), config );
});
return this;
}
function AutoResizer(el, config) {
if(this.clones) return;
this.config = $.extend({}, autoResize.defaults, config);
this.el = el;
this.nodeName = el[0].nodeName.toLowerCase();
this.previousScrollTop = null;
if (config.maxWidth === 'original') config.maxWidth = el.width();
if (config.minWidth === 'original') config.minWidth = el.width();
if (config.maxHeight === 'original') config.maxHeight = el.height();
if (config.minHeight === 'original') config.minHeight = el.height();
if (this.nodeName === 'textarea') {
el.css({
resize: 'none',
overflowY: 'none'
});
}
el.data('AutoResizer', this);
this.createClone();
this.injectClone();
this.bind();
}
AutoResizer.prototype = {
bind: function() {
var check = $.proxy(function(){
this.check();
return true;
}, this);
this.unbind();
this.el
.bind('keyup.autoResize', check)
//.bind('keydown.autoResize', check)
.bind('change.autoResize', check);
this.check(null, true);
},
unbind: function() {
this.el.unbind('.autoResize');
},
createClone: function() {
var el = this.el,
self = this,
config = this.config;
this.clones = $();
if (config.minHeight !== 'original' || config.maxHeight !== 'original') {
this.hClone = el.clone().height('auto');
this.clones = this.clones.add(this.hClone);
}
if (config.minWidth !== 'original' || config.maxWidth !== 'original') {
this.wClone = $('<div/>').width('auto').css({
whiteSpace: 'nowrap',
'float': 'left'
});
this.clones = this.clones.add(this.wClone);
}
$.each(autoResize.cloneCSSProperties, function(i, p){
self.clones.css(p, el.css(p));
});
this.clones
.removeAttr('name')
.removeAttr('id')
.attr('tabIndex', -1)
.css(autoResize.cloneCSSValues)
.css('overflowY', 'scroll');
},
check: function(e, immediate) {
var config = this.config,
wClone = this.wClone,
hClone = this.hClone,
el = this.el,
value = el.val();
if (wClone) {
wClone.text(value);
// Calculate new width + whether to change
var cloneWidth = wClone.outerWidth(),
newWidth = (cloneWidth + config.extraSpace) >= config.minWidth ?
cloneWidth + config.extraSpace : config.minWidth,
currentWidth = el.width();
newWidth = Math.min(newWidth, config.maxWidth);
if (
(newWidth < currentWidth && newWidth >= config.minWidth) ||
(newWidth >= config.minWidth && newWidth <= config.maxWidth)
) {
config.onResize.call(el);
el.scrollLeft(0);
config.animate && !immediate ?
el.stop(1,1).animate({
width: newWidth
}, config.animate)
: el.width(newWidth);
}
}
if (hClone) {
if (newWidth) {
hClone.width(newWidth);
}
hClone.height(0).val(value).scrollTop(10000);
var scrollTop = hClone[0].scrollTop + config.extraSpace;
// Don't do anything if scrollTop hasen't changed:
if (this.previousScrollTop === scrollTop) {
return;
}
this.previousScrollTop = scrollTop;
if (scrollTop >= config.maxHeight) {
scrollTop = config.maxHeight;
}
if (scrollTop < config.minHeight) {
scrollTop = config.minHeight;
}
if(scrollTop == config.maxHeight && newWidth == config.maxWidth) {
el.css('overflowY', 'scroll');
}
else {
el.css('overflowY', 'hidden');
}
config.onResize.call(el);
// Either animate or directly apply height:
config.animate && !immediate ?
el.stop(1,1).animate({
height: scrollTop
}, config.animate)
: el.height(scrollTop);
}
},
destroy: function() {
this.unbind();
this.el.removeData('AutoResizer');
this.clones.remove();
delete this.el;
delete this.hClone;
delete this.wClone;
delete this.clones;
},
injectClone: function() {
(
autoResize.cloneContainer ||
(autoResize.cloneContainer = $('<arclones/>').appendTo('body'))
).empty().append(this.clones); //this should be refactored so that a node is never cloned more than once
}
};
})(jQuery);
/**
* SheetClip - Spreadsheet Clipboard Parser
* version 0.2
*
* This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice,
* Google Docs and Microsoft Excel.
*
* Copyright 2012, Marcin Warpechowski
* Licensed under the MIT license.
* http://github.com/warpech/sheetclip/
*/
/*jslint white: true*/
(function (global) {
"use strict";
function countQuotes(str) {
return str.split('"').length - 1;
}
global.SheetClip = {
parse: function (str) {
var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last;
rows = str.split('\n');
if (rows.length > 1 && rows[rows.length - 1] === '') {
rows.pop();
}
for (r = 0, rlen = rows.length; r < rlen; r += 1) {
rows[r] = rows[r].split('\t');
for (c = 0, clen = rows[r].length; c < clen; c += 1) {
if (!arr[a]) {
arr[a] = [];
}
if (multiline && c === 0) {
last = arr[a].length - 1;
arr[a][last] = arr[a][last] + '\n' + rows[r][0];
if (multiline && (countQuotes(rows[r][0]) & 1)) { //& 1 is a bitwise way of performing mod 2
multiline = false;
arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"');
}
}
else {
if (c === clen - 1 && rows[r][c].indexOf('"') === 0) {
arr[a].push(rows[r][c].substring(1).replace(/""/g, '"'));
multiline = true;
}
else {
arr[a].push(rows[r][c].replace(/""/g, '"'));
multiline = false;
}
}
}
if (!multiline) {
a += 1;
}
}
return arr;
},
stringify: function (arr) {
var r, rlen, c, clen, str = '', val;
for (r = 0, rlen = arr.length; r < rlen; r += 1) {
for (c = 0, clen = arr[r].length; c < clen; c += 1) {
if (c > 0) {
str += '\t';
}
val = arr[r][c];
if (typeof val === 'string') {
if (val.indexOf('\n') > -1) {
str += '"' + val.replace(/"/g, '""') + '"';
}
else {
str += val;
}
}
else if (val === null || val === void 0) { //void 0 resolves to undefined
str += '';
}
else {
str += val;
}
}
str += '\n';
}
return str;
}
};
}(window));
/**
* CopyPaste.js
* Creates a textarea that stays hidden on the page and gets focused when user presses CTRL while not having a form input focused
* In future we may implement a better driver when better APIs are available
* @constructor
*/
var CopyPaste = (function () {
var instance;
return {
getInstance: function () {
if (!instance) {
instance = new CopyPasteClass();
} else if (instance.hasBeenDestroyed()){
instance.init();
}
instance.refCounter++;
return instance;
}
};
})();
function CopyPasteClass() {
this.refCounter = 0;
this.init();
}
CopyPasteClass.prototype.init = function () {
var that = this
, style
, parent;
this.copyCallbacks = [];
this.cutCallbacks = [];
this.pasteCallbacks = [];
this.listenerElement = document.documentElement;
parent = document.body;
if (document.getElementById('CopyPasteDiv')) {
this.elDiv = document.getElementById('CopyPasteDiv');
this.elTextarea = this.elDiv.firstChild;
}
else {
this.elDiv = document.createElement('DIV');
this.elDiv.id = 'CopyPasteDiv';
style = this.elDiv.style;
style.position = 'fixed';
style.top = 0;
style.left = 0;
parent.appendChild(this.elDiv);
this.elTextarea = document.createElement('TEXTAREA');
this.elTextarea.className = 'copyPaste';
style = this.elTextarea.style;
style.width = '1px';
style.height = '1px';
this.elDiv.appendChild(this.elTextarea);
if (typeof style.opacity !== 'undefined') {
style.opacity = 0;
}
else {
/*@cc_on @if (@_jscript)
if(typeof style.filter === 'string') {
style.filter = 'alpha(opacity=0)';
}
@end @*/
}
}
this.keydownListener = function (event) {
var isCtrlDown = false;
if (event.metaKey) { //mac
isCtrlDown = true;
}
else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { //pc
isCtrlDown = true;
}
if (isCtrlDown) {
if (document.activeElement !== that.elTextarea && (that.getSelectionText() != '' || ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(document.activeElement.nodeName) != -1)) {
return; //this is needed by fragmentSelection in Handsontable. Ignore copypaste.js behavior if fragment of cell text is selected
}
that.selectNodeText(that.elTextarea);
setTimeout(function () {
that.selectNodeText(that.elTextarea);
}, 0);
}
/* 67 = c
* 86 = v
* 88 = x
*/
if (isCtrlDown && (event.keyCode === 67 || event.keyCode === 86 || event.keyCode === 88)) {
// that.selectNodeText(that.elTextarea);
if (event.keyCode === 88) { //works in all browsers, incl. Opera < 12.12
setTimeout(function () {
that.triggerCut(event);
}, 0);
}
else if (event.keyCode === 86) {
setTimeout(function () {
that.triggerPaste(event);
}, 0);
}
}
}
this._bindEvent(this.listenerElement, 'keydown', this.keydownListener);
};
//http://jsperf.com/textara-selection
//http://stackoverflow.com/questions/1502385/how-can-i-make-this-code-work-in-ie
CopyPasteClass.prototype.selectNodeText = function (el) {
el.select();
};
//http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text
CopyPasteClass.prototype.getSelectionText = function () {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
};
CopyPasteClass.prototype.copyable = function (str) {
if (typeof str !== 'string' && str.toString === void 0) {
throw new Error('copyable requires string parameter');
}
this.elTextarea.value = str;
};
/*CopyPasteClass.prototype.onCopy = function (fn) {
this.copyCallbacks.push(fn);
};*/
CopyPasteClass.prototype.onCut = function (fn) {
this.cutCallbacks.push(fn);
};
CopyPasteClass.prototype.onPaste = function (fn) {
this.pasteCallbacks.push(fn);
};
CopyPasteClass.prototype.removeCallback = function (fn) {
var i, ilen;
for (i = 0, ilen = this.copyCallbacks.length; i < ilen; i++) {
if (this.copyCallbacks[i] === fn) {
this.copyCallbacks.splice(i, 1);
return true;
}
}
for (i = 0, ilen = this.cutCallbacks.length; i < ilen; i++) {
if (this.cutCallbacks[i] === fn) {
this.cutCallbacks.splice(i, 1);
return true;
}
}
for (i = 0, ilen = this.pasteCallbacks.length; i < ilen; i++) {
if (this.pasteCallbacks[i] === fn) {
this.pasteCallbacks.splice(i, 1);
return true;
}
}
return false;
};
CopyPasteClass.prototype.triggerCut = function (event) {
var that = this;
if (that.cutCallbacks) {
setTimeout(function () {
for (var i = 0, ilen = that.cutCallbacks.length; i < ilen; i++) {
that.cutCallbacks[i](event);
}
}, 50);
}
};
CopyPasteClass.prototype.triggerPaste = function (event, str) {
var that = this;
if (that.pasteCallbacks) {
setTimeout(function () {
var val = (str || that.elTextarea.value).replace(/\n$/, ''); //remove trailing newline
for (var i = 0, ilen = that.pasteCallbacks.length; i < ilen; i++) {
that.pasteCallbacks[i](val, event);
}
}, 50);
}
};
CopyPasteClass.prototype.destroy = function () {
if(!this.hasBeenDestroyed() && --this.refCounter == 0){
if (this.elDiv && this.elDiv.parentNode) {
this.elDiv.parentNode.removeChild(this.elDiv);
}
this._unbindEvent(this.listenerElement, 'keydown', this.keydownListener);
}
};
CopyPasteClass.prototype.hasBeenDestroyed = function () {
return !this.refCounter;
};
//old version used this:
// - http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
// - http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
//but that cannot work with jQuery.trigger
CopyPasteClass.prototype._bindEvent = (function () {
if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests)
return function (elem, type, cb) {
$(elem).on(type + '.copypaste', cb);
};
}
else {
return function (elem, type, cb) {
elem.addEventListener(type, cb, false); //sorry, IE8 will only work with jQuery
};
}
})();
CopyPasteClass.prototype._unbindEvent = (function () {
if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests)
return function (elem, type, cb) {
$(elem).off(type + '.copypaste', cb);
};
}
else {
return function (elem, type, cb) {
elem.removeEventListener(type, cb, false); //sorry, IE8 will only work with jQuery
};
}
})();
// json-patch-duplex.js 0.3.6
// (c) 2013 Joachim Wester
// MIT license
var jsonpatch;
(function (jsonpatch) {
var objOps = {
add: function (obj, key) {
obj[key] = this.value;
return true;
},
remove: function (obj, key) {
delete obj[key];
return true;
},
replace: function (obj, key) {
obj[key] = this.value;
return true;
},
move: function (obj, key, tree) {
var temp = { op: "_get", path: this.from };
apply(tree, [temp]);
apply(tree, [
{ op: "remove", path: this.from }
]);
apply(tree, [
{ op: "add", path: this.path, value: temp.value }
]);
return true;
},
copy: function (obj, key, tree) {
var temp = { op: "_get", path: this.from };
apply(tree, [temp]);
apply(tree, [
{ op: "add", path: this.path, value: temp.value }
]);
return true;
},
test: function (obj, key) {
return (JSON.stringify(obj[key]) === JSON.stringify(this.value));
},
_get: function (obj, key) {
this.value = obj[key];
}
};
var arrOps = {
add: function (arr, i) {
arr.splice(i, 0, this.value);
return true;
},
remove: function (arr, i) {
arr.splice(i, 1);
return true;
},
replace: function (arr, i) {
arr[i] = this.value;
return true;
},
move: objOps.move,
copy: objOps.copy,
test: objOps.test,
_get: objOps._get
};
var observeOps = {
add: function (patches, path) {
var patch = {
op: "add",
path: path + escapePathComponent(this.name),
value: this.object[this.name]
};
patches.push(patch);
},
'delete': function (patches, path) {
var patch = {
op: "remove",
path: path + escapePathComponent(this.name)
};
patches.push(patch);
},
update: function (patches, path) {
var patch = {
op: "replace",
path: path + escapePathComponent(this.name),
value: this.object[this.name]
};
patches.push(patch);
}
};
function escapePathComponent(str) {
if (str.indexOf('/') === -1 && str.indexOf('~') === -1)
return str;
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function _getPathRecursive(root, obj) {
var found;
for (var key in root) {
if (root.hasOwnProperty(key)) {
if (root[key] === obj) {
return escapePathComponent(key) + '/';
} else if (typeof root[key] === 'object') {
found = _getPathRecursive(root[key], obj);
if (found != '') {
return escapePathComponent(key) + '/' + found;
}
}
}
}
return '';
}
function getPath(root, obj) {
if (root === obj) {
return '/';
}
var path = _getPathRecursive(root, obj);
if (path === '') {
throw new Error("Object not found in root");
}
return '/' + path;
}
var beforeDict = [];
jsonpatch.intervals;
var Mirror = (function () {
function Mirror(obj) {
this.observers = [];
this.obj = obj;
}
return Mirror;
})();
var ObserverInfo = (function () {
function ObserverInfo(callback, observer) {
this.callback = callback;
this.observer = observer;
}
return ObserverInfo;
})();
function getMirror(obj) {
for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
if (beforeDict[i].obj === obj) {
return beforeDict[i];
}
}
}
function getObserverFromMirror(mirror, callback) {
for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
if (mirror.observers[j].callback === callback) {
return mirror.observers[j].observer;
}
}
}
function removeObserverFromMirror(mirror, observer) {
for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
if (mirror.observers[j].observer === observer) {
mirror.observers.splice(j, 1);
return;
}
}
}
function unobserve(root, observer) {
generate(observer);
if (Object.observe) {
_unobserve(observer, root);
} else {
clearTimeout(observer.next);
}
var mirror = getMirror(root);
removeObserverFromMirror(mirror, observer);
}
jsonpatch.unobserve = unobserve;
function observe(obj, callback) {
var patches = [];
var root = obj;
var observer;
var mirror = getMirror(obj);
if (!mirror) {
mirror = new Mirror(obj);
beforeDict.push(mirror);
} else {
observer = getObserverFromMirror(mirror, callback);
}
if (observer) {
return observer;
}
if (Object.observe) {
observer = function (arr) {
//This "refresh" is needed to begin observing new object properties
_unobserve(observer, obj);
_observe(observer, obj);
var a = 0, alen = arr.length;
while (a < alen) {
if (!(arr[a].name === 'length' && _isArray(arr[a].object)) && !(arr[a].name === '__Jasmine_been_here_before__')) {
var type = arr[a].type;
switch (type) {
case 'new':
type = 'add';
break;
case 'deleted':
type = 'delete';
break;
case 'updated':
type = 'update';
break;
}
observeOps[type].call(arr[a], patches, getPath(root, arr[a].object));
}
a++;
}
if (patches) {
if (callback) {
callback(patches);
}
}
observer.patches = patches;
patches = [];
};
} else {
observer = {};
mirror.value = JSON.parse(JSON.stringify(obj));
if (callback) {
//callbacks.push(callback); this has no purpose
observer.callback = callback;
observer.next = null;
var intervals = this.intervals || [100, 1000, 10000, 60000];
var currentInterval = 0;
var dirtyCheck = function () {
generate(observer);
};
var fastCheck = function () {
clearTimeout(observer.next);
observer.next = setTimeout(function () {
dirtyCheck();
currentInterval = 0;
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
}, 0);
};
var slowCheck = function () {
dirtyCheck();
if (currentInterval == intervals.length)
currentInterval = intervals.length - 1;
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
};
if (typeof window !== 'undefined') {
if (window.addEventListener) {
window.addEventListener('mousedown', fastCheck);
window.addEventListener('mouseup', fastCheck);
window.addEventListener('keydown', fastCheck);
} else {
window.attachEvent('onmousedown', fastCheck);
window.attachEvent('onmouseup', fastCheck);
window.attachEvent('onkeydown', fastCheck);
}
}
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
}
}
observer.patches = patches;
observer.object = obj;
mirror.observers.push(new ObserverInfo(callback, observer));
return _observe(observer, obj);
}
jsonpatch.observe = observe;
/// Listen to changes on an object tree, accumulate patches
function _observe(observer, obj) {
if (Object.observe) {
Object.observe(obj, observer);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var v = obj[key];
if (v && typeof (v) === "object") {
_observe(observer, v);
}
}
}
}
return observer;
}
function _unobserve(observer, obj) {
if (Object.observe) {
Object.unobserve(obj, observer);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var v = obj[key];
if (v && typeof (v) === "object") {
_unobserve(observer, v);
}
}
}
}
return observer;
}
function generate(observer) {
if (Object.observe) {
Object.deliverChangeRecords(observer);
} else {
var mirror;
for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
if (beforeDict[i].obj === observer.object) {
mirror = beforeDict[i];
break;
}
}
_generate(mirror.value, observer.object, observer.patches, "");
}
var temp = observer.patches;
if (temp.length > 0) {
observer.patches = [];
if (observer.callback) {
observer.callback(temp);
}
}
return temp;
}
jsonpatch.generate = generate;
var _objectKeys;
if (Object.keys) {
_objectKeys = Object.keys;
} else {
_objectKeys = function (obj) {
var keys = [];
for (var o in obj) {
if (obj.hasOwnProperty(o)) {
keys.push(o);
}
}
return keys;
};
}
// Dirty check if obj is different from mirror, generate patches and update mirror
function _generate(mirror, obj, patches, path) {
var newKeys = _objectKeys(obj);
var oldKeys = _objectKeys(mirror);
var changed = false;
var deleted = false;
for (var t = oldKeys.length - 1; t >= 0; t--) {
var key = oldKeys[t];
var oldVal = mirror[key];
if (obj.hasOwnProperty(key)) {
var newVal = obj[key];
if (oldVal instanceof Object) {
_generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key));
} else {
if (oldVal != newVal) {
changed = true;
patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: newVal });
mirror[key] = newVal;
}
}
} else {
patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) });
delete mirror[key];
deleted = true;
}
}
if (!deleted && newKeys.length == oldKeys.length) {
return;
}
for (var t = 0; t < newKeys.length; t++) {
var key = newKeys[t];
if (!mirror.hasOwnProperty(key)) {
patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: obj[key] });
mirror[key] = JSON.parse(JSON.stringify(obj[key]));
}
}
}
var _isArray;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (obj) {
return obj.push && typeof obj.length === 'number';
};
}
/// Apply a json-patch operation on an object tree
function apply(tree, patches) {
var result = false, p = 0, plen = patches.length, patch;
while (p < plen) {
patch = patches[p];
// Find the object
var keys = patch.path.split('/');
var obj = tree;
var t = 1;
var len = keys.length;
while (true) {
if (_isArray(obj)) {
var index = parseInt(keys[t], 10);
t++;
if (t >= len) {
result = arrOps[patch.op].call(patch, obj, index, tree);
break;
}
obj = obj[index];
} else {
var key = keys[t];
if (key.indexOf('~') != -1)
key = key.replace(/~1/g, '/').replace(/~0/g, '~');
t++;
if (t >= len) {
result = objOps[patch.op].call(patch, obj, key, tree);
break;
}
obj = obj[key];
}
}
p++;
}
return result;
}
jsonpatch.apply = apply;
})(jsonpatch || (jsonpatch = {}));
if (typeof exports !== "undefined") {
exports.apply = jsonpatch.apply;
exports.observe = jsonpatch.observe;
exports.unobserve = jsonpatch.unobserve;
exports.generate = jsonpatch.generate;
}
Handsontable.PluginHookClass = (function () {
var Hooks = function () {
return {
// Hooks
beforeInitWalkontable: [],
beforeInit: [],
beforeRender: [],
beforeChange: [],
beforeRemoveCol: [],
beforeRemoveRow: [],
beforeValidate: [],
beforeGet: [],
beforeSet: [],
beforeGetCellMeta: [],
beforeAutofill: [],
beforeKeyDown: [],
beforeColumnSort: [],
afterInit : [],
afterLoadData : [],
afterUpdateSettings: [],
afterRender : [],
afterRenderer : [],
afterChange : [],
afterValidate: [],
afterGetCellMeta: [],
afterGetColHeader: [],
afterGetColWidth: [],
afterDestroy: [],
afterRemoveRow: [],
afterCreateRow: [],
afterRemoveCol: [],
afterCreateCol: [],
afterColumnResize: [],
afterColumnMove: [],
afterColumnSort: [],
afterDeselect: [],
afterSelection: [],
afterSelectionByProp: [],
afterSelectionEnd: [],
afterSelectionEndByProp: [],
afterCopyLimit: [],
afterOnCellMouseDown: [],
afterOnCellMouseOver: [],
afterOnCellCornerMouseDown: [],
afterScrollVertically: [],
afterScrollHorizontally: [],
// Modifiers
modifyCol: []
}
};
var legacy = {
onBeforeChange: "beforeChange",
onChange: "afterChange",
onCreateRow: "afterCreateRow",
onCreateCol: "afterCreateCol",
onSelection: "afterSelection",
onCopyLimit: "afterCopyLimit",
onSelectionEnd: "afterSelectionEnd",
onSelectionByProp: "afterSelectionByProp",
onSelectionEndByProp: "afterSelectionEndByProp"
};
function PluginHookClass() {
this.hooks = Hooks();
this.legacy = legacy;
}
PluginHookClass.prototype.add = function (key, fn) {
//if fn is array, run this for all the array items
if (Handsontable.helper.isArray(fn)) {
for (var i = 0, len = fn.length; i < len; i++) {
this.add(key, fn[i]);
}
}
else {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
if (typeof this.hooks[key] === "undefined") {
this.hooks[key] = [];
}
if (this.hooks[key].indexOf(fn) == -1) {
this.hooks[key].push(fn); //only add a hook if it has not already be added (adding the same hook twice is now silently ignored)
}
}
return this;
};
PluginHookClass.prototype.once = function(key, fn){
if(Handsontable.helper.isArray(fn)){
for(var i = 0, len = fn.length; i < len; i++){
fn[i].runOnce = true;
this.add(key, fn[i]);
}
} else {
fn.runOnce = true;
this.add(key, fn);
}
};
PluginHookClass.prototype.remove = function (key, fn) {
var status = false;
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
if (typeof this.hooks[key] !== 'undefined') {
for (var i = 0, leni = this.hooks[key].length; i < leni; i++) {
if (this.hooks[key][i] == fn) {
delete this.hooks[key][i].runOnce;
this.hooks[key].splice(i, 1);
status = true;
break;
}
}
}
return status;
};
PluginHookClass.prototype.run = function (instance, key, p1, p2, p3, p4, p5) {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
//performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
if (typeof this.hooks[key] !== 'undefined') {
//Make a copy of handler array
var handlers = Array.prototype.slice.call(this.hooks[key]);
for (var i = 0, leni = handlers.length; i < leni; i++) {
handlers[i].call(instance, p1, p2, p3, p4, p5);
if(handlers[i].runOnce){
this.remove(key, handlers[i]);
}
}
}
};
PluginHookClass.prototype.execute = function (instance, key, p1, p2, p3, p4, p5) {
var res, handlers;
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
//performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
if (typeof this.hooks[key] !== 'undefined') {
handlers = Array.prototype.slice.call(this.hooks[key]);
for (var i = 0, leni = handlers.length; i < leni; i++) {
res = handlers[i].call(instance, p1, p2, p3, p4, p5);
if (res !== void 0) {
p1 = res;
}
if(handlers[i].runOnce){
this.remove(key, handlers[i]);
}
if(res === false){ //if any handler returned false
return false; //event has been cancelled and further execution of handler queue is being aborted
}
}
}
return p1;
};
return PluginHookClass;
})();
Handsontable.PluginHooks = new Handsontable.PluginHookClass();
(function (Handsontable) {
function HandsontableAutoColumnSize() {
var plugin = this
, sampleCount = 5; //number of samples to take of each value length
this.beforeInit = function () {
var instance = this;
instance.autoColumnWidths = [];
if (instance.getSettings().autoColumnSize !== false) {
if (!instance.autoColumnSizeTmp) {
instance.autoColumnSizeTmp = {
table: null,
tableStyle: null,
theadTh: null,
tbody: null,
container: null,
containerStyle: null,
determineBeforeNextRender: true
};
instance.addHook('beforeRender', htAutoColumnSize.determineIfChanged);
instance.addHook('afterGetColWidth', htAutoColumnSize.getColWidth);
instance.addHook('afterDestroy', htAutoColumnSize.afterDestroy);
instance.determineColumnWidth = plugin.determineColumnWidth;
}
} else {
if (instance.autoColumnSizeTmp) {
instance.removeHook('beforeRender', htAutoColumnSize.determineIfChanged);
instance.removeHook('afterGetColWidth', htAutoColumnSize.getColWidth);
instance.removeHook('afterDestroy', htAutoColumnSize.afterDestroy);
delete instance.determineColumnWidth;
plugin.afterDestroy.call(instance);
}
}
};
this.determineIfChanged = function (force) {
if (force) {
htAutoColumnSize.determineColumnsWidth.apply(this, arguments);
}
};
this.determineColumnWidth = function (col) {
var instance = this
, tmp = instance.autoColumnSizeTmp;
if (!tmp.container) {
createTmpContainer.call(tmp, instance);
}
tmp.container.className = instance.rootElement[0].className + ' htAutoColumnSize';
tmp.table.className = instance.$table[0].className;
var rows = instance.countRows();
var samples = {};
var maxLen = 0;
for (var r = 0; r < rows; r++) {
var value = Handsontable.helper.stringify(instance.getDataAtCell(r, col));
var len = value.length;
if (len > maxLen) {
maxLen = len;
}
if (!samples[len]) {
samples[len] = {
needed: sampleCount,
strings: []
};
}
if (samples[len].needed) {
samples[len].strings.push({value: value, row: r});
samples[len].needed--;
}
}
var settings = instance.getSettings();
if (settings.colHeaders) {
instance.view.appendColHeader(col, tmp.theadTh); //TH innerHTML
}
instance.view.wt.wtDom.empty(tmp.tbody);
for (var i in samples) {
if (samples.hasOwnProperty(i)) {
for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) {
var row = samples[i].strings[j].row;
var cellProperties = instance.getCellMeta(row, col);
cellProperties.col = col;
cellProperties.row = row;
var renderer = instance.getCellRenderer(cellProperties);
var tr = document.createElement('tr');
var td = document.createElement('td');
renderer(instance, td, row, col, instance.colToProp(col), samples[i].strings[j].value, cellProperties);
r++;
tr.appendChild(td);
tmp.tbody.appendChild(tr);
}
}
}
var parent = instance.rootElement[0].parentNode;
parent.appendChild(tmp.container);
var width = instance.view.wt.wtDom.outerWidth(tmp.table);
parent.removeChild(tmp.container);
if (!settings.nativeScrollbars) { //with native scrollbars a cell size can safely exceed the width of the viewport
var maxWidth = instance.view.wt.wtViewport.getViewportWidth() - 2; //2 is some overhead for cell border
if (width > maxWidth) {
width = maxWidth;
}
}
return width;
};
this.determineColumnsWidth = function () {
var instance = this;
var settings = this.getSettings();
if (settings.autoColumnSize || !settings.colWidths) {
var cols = this.countCols();
for (var c = 0; c < cols; c++) {
if (!instance._getColWidthFromSettings(c)) {
this.autoColumnWidths[c] = plugin.determineColumnWidth.call(instance, c);
}
}
}
};
this.getColWidth = function (col, response) {
if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > response.width) {
response.width = this.autoColumnWidths[col];
}
};
this.afterDestroy = function () {
var instance = this;
if (instance.autoColumnSizeTmp && instance.autoColumnSizeTmp.container && instance.autoColumnSizeTmp.container.parentNode) {
instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container);
}
instance.autoColumnSizeTmp = null;
};
function createTmpContainer(instance) {
var d = document
, tmp = this;
tmp.table = d.createElement('table');
tmp.theadTh = d.createElement('th');
tmp.table.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(tmp.theadTh);
tmp.tableStyle = tmp.table.style;
tmp.tableStyle.tableLayout = 'auto';
tmp.tableStyle.width = 'auto';
tmp.tbody = d.createElement('tbody');
tmp.table.appendChild(tmp.tbody);
tmp.container = d.createElement('div');
tmp.container.className = instance.rootElement[0].className + ' hidden';
tmp.containerStyle = tmp.container.style;
tmp.container.appendChild(tmp.table);
}
}
var htAutoColumnSize = new HandsontableAutoColumnSize();
Handsontable.PluginHooks.add('beforeInit', htAutoColumnSize.beforeInit);
Handsontable.PluginHooks.add('afterUpdateSettings', htAutoColumnSize.beforeInit);
})(Handsontable);
/**
* This plugin sorts the view by a column (but does not sort the data source!)
* @constructor
*/
function HandsontableColumnSorting() {
var plugin = this;
this.init = function (source) {
var instance = this;
var sortingSettings = instance.getSettings().columnSorting;
var sortingColumn, sortingOrder;
instance.sortingEnabled = !!(sortingSettings);
if (instance.sortingEnabled) {
instance.sortIndex = [];
var loadedSortingState = loadSortingState.call(instance);
if (typeof loadedSortingState != 'undefined') {
sortingColumn = loadedSortingState.sortColumn;
sortingOrder = loadedSortingState.sortOrder;
} else {
sortingColumn = sortingSettings.column;
sortingOrder = sortingSettings.sortOrder;
}
plugin.sortByColumn.call(instance, sortingColumn, sortingOrder);
instance.sort = function(){
var args = Array.prototype.slice.call(arguments);
return plugin.sortByColumn.apply(instance, args)
};
if (typeof instance.getSettings().observeChanges == 'undefined'){
enableObserveChangesPlugin.call(instance);
}
if (source == 'afterInit') {
bindColumnSortingAfterClick.call(instance);
instance.addHook('afterCreateRow', plugin.afterCreateRow);
instance.addHook('afterRemoveRow', plugin.afterRemoveRow);
instance.addHook('afterLoadData', plugin.init);
}
} else {
delete instance.sort;
instance.removeHook('afterCreateRow', plugin.afterCreateRow);
instance.removeHook('afterRemoveRow', plugin.afterRemoveRow);
instance.removeHook('afterLoadData', plugin.init);
}
};
this.setSortingColumn = function (col, order) {
var instance = this;
if (typeof col == 'undefined') {
delete instance.sortColumn;
delete instance.sortOrder;
return;
} else if (instance.sortColumn === col && typeof order == 'undefined') {
instance.sortOrder = !instance.sortOrder;
} else {
instance.sortOrder = typeof order != 'undefined' ? order : true;
}
instance.sortColumn = col;
};
this.sortByColumn = function (col, order) {
var instance = this;
plugin.setSortingColumn.call(instance, col, order);
if(typeof instance.sortColumn == 'undefined'){
return;
}
instance.PluginHooks.run('beforeColumnSort', instance.sortColumn, instance.sortOrder);
plugin.sort.call(instance);
instance.render();
saveSortingState.call(instance);
instance.PluginHooks.run('afterColumnSort', instance.sortColumn, instance.sortOrder);
};
var saveSortingState = function () {
var instance = this;
var sortingState = {};
if (typeof instance.sortColumn != 'undefined') {
sortingState.sortColumn = instance.sortColumn;
}
if (typeof instance.sortOrder != 'undefined') {
sortingState.sortOrder = instance.sortOrder;
}
if (sortingState.hasOwnProperty('sortColumn') || sortingState.hasOwnProperty('sortOrder')) {
instance.PluginHooks.run('persistentStateSave', 'columnSorting', sortingState);
}
};
var loadSortingState = function () {
var instance = this;
var storedState = {};
instance.PluginHooks.run('persistentStateLoad', 'columnSorting', storedState);
return storedState.value;
};
var bindColumnSortingAfterClick = function () {
var instance = this;
instance.rootElement.on('click.handsontable', '.columnSorting', function (e) {
if (instance.view.wt.wtDom.hasClass(e.target, 'columnSorting')) {
var col = getColumn(e.target);
plugin.sortByColumn.call(instance, col);
}
});
function countRowHeaders() {
var THs = instance.view.TBODY.querySelector('tr').querySelectorAll('th');
return THs.length;
}
function getColumn(target) {
var TH = instance.view.wt.wtDom.closest(target, 'TH');
return instance.view.wt.wtDom.index(TH) - countRowHeaders();
}
};
function enableObserveChangesPlugin () {
var instance = this;
instance.registerTimeout('enableObserveChanges', function(){
instance.updateSettings({
observeChanges: true
});
}, 0);
}
function defaultSort(sortOrder) {
return function (a, b) {
if (a[1] === b[1]) {
return 0;
}
if (a[1] === null) {
return 1;
}
if (b[1] === null) {
return -1;
}
if (a[1] < b[1]) return sortOrder ? -1 : 1;
if (a[1] > b[1]) return sortOrder ? 1 : -1;
return 0;
}
}
function dateSort(sortOrder) {
return function (a, b) {
if (a[1] === b[1]) {
return 0;
}
if (a[1] === null) {
return 1;
}
if (b[1] === null) {
return -1;
}
var aDate = new Date(a[1]);
var bDate = new Date(b[1]);
if (aDate < bDate) return sortOrder ? -1 : 1;
if (aDate > bDate) return sortOrder ? 1 : -1;
return 0;
}
}
this.sort = function () {
var instance = this;
if (typeof instance.sortOrder == 'undefined') {
return;
}
instance.sortingEnabled = false; //this is required by translateRow plugin hook
instance.sortIndex.length = 0;
var colOffset = this.colOffset();
for (var i = 0, ilen = this.countRows() - instance.getSettings()['minSpareRows']; i < ilen; i++) {
this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]);
}
var colMeta = instance.getCellMeta(0, instance.sortColumn);
var sortFunction;
switch (colMeta.type) {
case 'date':
sortFunction = dateSort;
break;
default:
sortFunction = defaultSort;
}
this.sortIndex.sort(sortFunction(instance.sortOrder));
//Append spareRows
for(var i = this.sortIndex.length; i < instance.countRows(); i++){
this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]);
}
instance.sortingEnabled = true; //this is required by translateRow plugin hook
};
this.translateRow = function (row) {
var instance = this;
if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length && instance.sortIndex[row]) {
return instance.sortIndex[row][0];
}
return row;
};
this.onBeforeGetSet = function (getVars) {
var instance = this;
getVars.row = plugin.translateRow.call(instance, getVars.row);
};
this.untranslateRow = function (row) {
var instance = this;
if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length) {
for (var i = 0; i < instance.sortIndex.length; i++) {
if (instance.sortIndex[i][0] == row) {
return i;
}
}
}
};
this.getColHeader = function (col, TH) {
if (this.getSettings().columnSorting) {
this.view.wt.wtDom.addClass(TH.querySelector('.colHeader'), 'columnSorting');
}
};
function isSorted(instance){
return typeof instance.sortColumn != 'undefined';
}
this.afterCreateRow = function(index, amount){
var instance = this;
if(!isSorted(instance)){
return;
}
for(var i = 0; i < instance.sortIndex.length; i++){
if (instance.sortIndex[i][0] >= index){
instance.sortIndex[i][0] += amount;
}
}
for(var i=0; i < amount; i++){
instance.sortIndex.splice(index+i, 0, [index+i, instance.getData()[index+i][instance.sortColumn + instance.colOffset()]]);
}
saveSortingState.call(instance);
};
this.afterRemoveRow = function(index, amount){
var instance = this;
if(!isSorted(instance)){
return;
}
var physicalRemovedIndex = plugin.translateRow.call(instance, index);
instance.sortIndex.splice(index, amount);
for(var i = 0; i < instance.sortIndex.length; i++){
if (instance.sortIndex[i][0] > physicalRemovedIndex){
instance.sortIndex[i][0] -= amount;
}
}
saveSortingState.call(instance);
};
this.afterChangeSort = function (changes/*, source*/) {
var instance = this;
var sortColumnChanged = false;
var selection = {};
if (!changes) {
return;
}
for (var i = 0; i < changes.length; i++) {
if (changes[i][1] == instance.sortColumn) {
sortColumnChanged = true;
selection.row = plugin.translateRow.call(instance, changes[i][0]);
selection.col = changes[i][1];
break;
}
}
if (sortColumnChanged) {
setTimeout(function () {
plugin.sort.call(instance);
instance.render();
instance.selectCell(plugin.untranslateRow.call(instance, selection.row), selection.col);
}, 0);
}
};
}
var htSortColumn = new HandsontableColumnSorting();
Handsontable.PluginHooks.add('afterInit', function () {
htSortColumn.init.call(this, 'afterInit')
});
Handsontable.PluginHooks.add('afterUpdateSettings', function () {
htSortColumn.init.call(this, 'afterUpdateSettings')
});
Handsontable.PluginHooks.add('beforeGet', htSortColumn.onBeforeGetSet);
Handsontable.PluginHooks.add('beforeSet', htSortColumn.onBeforeGetSet);
Handsontable.PluginHooks.add('afterGetColHeader', htSortColumn.getColHeader);
(function (Handsontable) {
'use strict';
function ContextMenu(instance, customOptions){
this.instance = instance;
var contextMenu = this;
this.menu = createMenu();
this.enabled = true;
this.bindMouseEvents();
this.bindTableEvents();
this.instance.addHook('afterDestroy', function () {
contextMenu.destroy();
});
this.defaultOptions = {
items: {
'row_above': {
name: 'Insert row above',
callback: function(key, selection){
this.alter("insert_row", selection.start.row());
},
disabled: function () {
return this.countRows() >= this.getSettings().maxRows;
}
},
'row_below': {
name: 'Insert row below',
callback: function(key, selection){
this.alter("insert_row", selection.end.row() + 1);
},
disabled: function () {
return this.countRows() >= this.getSettings().maxRows;
}
},
"hsep1": ContextMenu.SEPARATOR,
'col_left': {
name: 'Insert column on the left',
callback: function(key, selection){
this.alter("insert_col", selection.start.col());
},
disabled: function () {
return this.countCols() >= this.getSettings().maxCols;
}
},
'col_right': {
name: 'Insert column on the right',
callback: function(key, selection){
this.alter("insert_col", selection.end.col() + 1);
},
disabled: function () {
return this.countCols() >= this.getSettings().maxCols;
}
},
"hsep2": ContextMenu.SEPARATOR,
'remove_row': {
name: 'Remove row',
callback: function(key, selection){
var amount = selection.end.row() - selection.start.row() + 1;
this.alter("remove_row", selection.start.row(), amount);
}
},
'remove_col': {
name: 'Remove column',
callback: function(key, selection){
var amount = selection.end.col() - selection.start.col() + 1;
this.alter("remove_col", selection.start.col(), amount);
}
},
"hsep3": ContextMenu.SEPARATOR,
'undo': {
name: 'Undo',
callback: function(){
this.undo();
},
disabled: function () {
return this.undoRedo && !this.undoRedo.isUndoAvailable();
}
},
'redo': {
name: 'Redo',
callback: function(){
this.redo();
},
disabled: function () {
return this.undoRedo && !this.undoRedo.isRedoAvailable();
}
}
}
};
this.options = {};
Handsontable.helper.extend(this.options, this.defaultOptions);
this.updateOptions(customOptions);
function createMenu(){
var menu = $('body > .htContextMenu')[0];
if(!menu){
menu = document.createElement('DIV');
Handsontable.Dom.addClass(menu, 'htContextMenu');
document.getElementsByTagName('body')[0].appendChild(menu);
}
return menu;
}
}
ContextMenu.prototype.bindMouseEvents = function (){
function contextMenuOpenListener(event){
event.preventDefault();
if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){
return;
}
this.show(event.pageY, event.pageX);
$(document).on('mousedown.htContextMenu', Handsontable.helper.proxy(ContextMenu.prototype.close, this));
}
this.instance.rootElement.on('contextmenu.htContextMenu', Handsontable.helper.proxy(contextMenuOpenListener, this));
};
ContextMenu.prototype.bindTableEvents = function () {
var that = this;
this._afterScrollCallback = function () {
that.close();
};
this.instance.addHook('afterScrollVertically', this._afterScrollCallback);
this.instance.addHook('afterScrollHorizontally', this._afterScrollCallback);
};
ContextMenu.prototype.unbindTableEvents = function () {
var that = this;
if(this._afterScrollCallback){
this.instance.removeHook('afterScrollVertically', this._afterScrollCallback);
this.instance.removeHook('afterScrollHorizontally', this._afterScrollCallback);
this._afterScrollCallback = null;
}
};
ContextMenu.prototype.performAction = function (){
var hot = $(this.menu).handsontable('getInstance');
var selectedItemIndex = hot.getSelected()[0];
var selectedItem = hot.getData()[selectedItemIndex];
if (selectedItem.disabled === true || (typeof selectedItem.disabled == 'function' && selectedItem.disabled.call(this.instance) === true)){
return;
}
if(typeof selectedItem.callback != 'function'){
return;
}
var corners = this.instance.getSelected();
var normalizedSelection = ContextMenu.utils.normalizeSelection(corners);
selectedItem.callback.call(this.instance, selectedItem.key, normalizedSelection);
};
ContextMenu.prototype.unbindMouseEvents = function () {
this.instance.rootElement.off('contextmenu.htContextMenu');
$(document).off('mousedown.htContextMenu');
};
ContextMenu.prototype.show = function(top, left){
this.menu.style.display = 'block';
$(this.menu)
.off('mousedown.htContextMenu')
.on('mousedown.htContextMenu', Handsontable.helper.proxy(this.performAction, this));
$(this.menu).handsontable({
data: ContextMenu.utils.convertItemsToArray(this.getItems()),
colHeaders: false,
colWidths: [160],
readOnly: true,
copyPaste: false,
columns: [
{
data: 'name',
renderer: Handsontable.helper.proxy(this.renderer, this)
}
],
beforeKeyDown: Handsontable.helper.proxy(this.onBeforeKeyDown, this)
});
this.bindTableEvents();
this.setMenuPosition(top, left);
$(this.menu).handsontable('listen');
};
ContextMenu.prototype.close = function () {
this.hide();
$(document).off('mousedown.htContextMenu');
this.unbindTableEvents();
this.instance.listen();
};
ContextMenu.prototype.hide = function(){
this.menu.style.display = 'none';
$(this.menu).handsontable('destroy');
};
ContextMenu.prototype.renderer = function(instance, TD, row, col, prop, value, cellProperties){
var contextMenu = this;
var item = instance.getData()[row];
var wrapper = document.createElement('DIV');
Handsontable.Dom.empty(TD);
TD.appendChild(wrapper);
if(itemIsSeparator(item)){
Handsontable.Dom.addClass(TD, 'htSeparator');
} else {
Handsontable.Dom.fastInnerText(wrapper, value);
}
if (itemIsDisabled(item, contextMenu.instance)){
Handsontable.Dom.addClass(TD, 'htDisabled');
$(wrapper).on('mouseenter', function () {
instance.deselectCell();
});
} else {
Handsontable.Dom.removeClass(TD, 'htDisabled');
$(wrapper).on('mouseenter', function () {
instance.selectCell(row, col);
});
}
function itemIsSeparator(item){
return new RegExp(ContextMenu.SEPARATOR, 'i').test(item.name);
}
function itemIsDisabled(item, instance){
return item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(contextMenu.instance) === true);
}
};
ContextMenu.prototype.onBeforeKeyDown = function (event) {
var contextMenu = this;
var instance = $(contextMenu.menu).handsontable('getInstance');
var selection = instance.getSelected();
switch(event.keyCode){
case Handsontable.helper.keyCode.ESCAPE:
contextMenu.close();
event.preventDefault();
event.stopImmediatePropagation();
break;
case Handsontable.helper.keyCode.ENTER:
if(instance.getSelected()){
contextMenu.performAction();
contextMenu.close();
}
break;
case Handsontable.helper.keyCode.ARROW_DOWN:
if(!selection){
selectFirstCell(instance);
} else {
selectNextCell(selection[0], selection[1], instance);
}
event.preventDefault();
event.stopImmediatePropagation();
break;
case Handsontable.helper.keyCode.ARROW_UP:
if(!selection){
selectLastCell(instance);
} else {
selectPrevCell(selection[0], selection[1], instance);
}
event.preventDefault();
event.stopImmediatePropagation();
break;
}
function selectFirstCell(instance) {
var firstCell = instance.getCell(0, 0);
if(ContextMenu.utils.isSeparator(firstCell) || ContextMenu.utils.isDisabled(firstCell)){
selectNextCell(0, 0, instance);
} else {
instance.selectCell(0, 0);
}
}
function selectLastCell(instance) {
var lastRow = instance.countRows() - 1;
var lastCell = instance.getCell(lastRow, 0);
if(ContextMenu.utils.isSeparator(lastCell) || ContextMenu.utils.isDisabled(lastCell)){
selectPrevCell(lastRow, 0, instance);
} else {
instance.selectCell(lastRow, 0);
}
}
function selectNextCell(row, col, instance){
var nextRow = row + 1;
var nextCell = nextRow < instance.countRows() ? instance.getCell(nextRow, col) : null;
if(!nextCell){
return;
}
if(ContextMenu.utils.isSeparator(nextCell) || ContextMenu.utils.isDisabled(nextCell)){
selectNextCell(nextRow, col, instance);
} else {
instance.selectCell(nextRow, col);
}
}
function selectPrevCell(row, col, instance) {
var prevRow = row - 1;
var prevCell = prevRow >= 0 ? instance.getCell(prevRow, col) : null;
if (!prevCell) {
return;
}
if(ContextMenu.utils.isSeparator(prevCell) || ContextMenu.utils.isDisabled(prevCell)){
selectPrevCell(prevRow, col, instance);
} else {
instance.selectCell(prevRow, col);
}
}
};
ContextMenu.prototype.getItems = function () {
var items = {};
function Item(rawItem){
if(typeof rawItem == 'string'){
this.name = rawItem;
} else {
Handsontable.helper.extend(this, rawItem);
}
}
Item.prototype = this.options;
for(var itemName in this.options.items){
if(this.options.items.hasOwnProperty(itemName) && (!this.itemsFilter || this.itemsFilter.indexOf(itemName) != -1)){
items[itemName] = new Item(this.options.items[itemName]);
}
}
return items;
};
ContextMenu.prototype.updateOptions = function(newOptions){
newOptions = newOptions || {};
if(newOptions.items){
for(var itemName in newOptions.items){
var item = {};
if(newOptions.items.hasOwnProperty(itemName)) {
if(this.defaultOptions.items.hasOwnProperty(itemName)
&& Handsontable.helper.isObject(newOptions.items[itemName])){
Handsontable.helper.extend(item, this.defaultOptions.items[itemName]);
Handsontable.helper.extend(item, newOptions.items[itemName]);
newOptions.items[itemName] = item;
}
}
}
}
Handsontable.helper.extend(this.options, newOptions);
};
ContextMenu.prototype.setMenuPosition = function (cursorY, cursorX) {
var cursor = {
top: cursorY,
topRelative: cursorY - document.documentElement.scrollTop,
left: cursorX,
leftRelative:cursorX - document.documentElement.scrollLeft
};
if(this.menuFitsBelowCursor(cursor)){
this.positionMenuBelowCursor(cursor);
} else {
this.positionMenuAboveCursor(cursor);
}
if(this.menuFitsOnRightOfCursor(cursor)){
this.positionMenuOnRightOfCursor(cursor);
} else {
this.positionMenuOnLeftOfCursor(cursor);
}
};
ContextMenu.prototype.menuFitsBelowCursor = function (cursor) {
return cursor.topRelative + this.menu.offsetHeight <= document.documentElement.scrollTop + document.documentElement.clientHeight;
};
ContextMenu.prototype.menuFitsOnRightOfCursor = function (cursor) {
return cursor.leftRelative + this.menu.offsetWidth <= document.documentElement.scrollLeft + document.documentElement.clientWidth;
};
ContextMenu.prototype.positionMenuBelowCursor = function (cursor) {
this.menu.style.top = cursor.top + 'px';
};
ContextMenu.prototype.positionMenuAboveCursor = function (cursor) {
this.menu.style.top = (cursor.top - this.menu.offsetHeight) + 'px';
};
ContextMenu.prototype.positionMenuOnRightOfCursor = function (cursor) {
this.menu.style.left = cursor.left + 'px';
};
ContextMenu.prototype.positionMenuOnLeftOfCursor = function (cursor) {
this.menu.style.left = (cursor.left - this.menu.offsetWidth) + 'px';
};
ContextMenu.utils = {};
ContextMenu.utils.convertItemsToArray = function (items) {
var itemArray = [];
var item;
for(var itemName in items){
if(items.hasOwnProperty(itemName)){
if(typeof items[itemName] == 'string'){
item = {name: items[itemName]};
} else if (items[itemName].visible !== false) {
item = items[itemName];
} else {
continue;
}
item.key = itemName;
itemArray.push(item);
}
}
return itemArray;
};
ContextMenu.utils.normalizeSelection = function(corners){
var selection = {
start: new Handsontable.SelectionPoint(),
end: new Handsontable.SelectionPoint()
};
selection.start.row(Math.min(corners[0], corners[2]));
selection.start.col(Math.min(corners[1], corners[3]));
selection.end.row(Math.max(corners[0], corners[2]));
selection.end.col(Math.max(corners[1], corners[3]));
return selection;
};
ContextMenu.utils.isSeparator = function (cell) {
return Handsontable.Dom.hasClass(cell, 'htSeparator');
};
ContextMenu.utils.isDisabled = function (cell) {
return Handsontable.Dom.hasClass(cell, 'htDisabled');
};
ContextMenu.prototype.enable = function () {
if(!this.enabled){
this.enabled = true;
this.bindMouseEvents();
}
};
ContextMenu.prototype.disable = function () {
if(this.enabled){
this.enabled = false;
this.close();
this.unbindMouseEvents();
this.unbindTableEvents();
}
};
ContextMenu.prototype.destroy = function () {
this.close();
this.unbindMouseEvents();
this.unbindTableEvents();
if(!this.isMenuEnabledByOtherHotInstance()){
this.removeMenu();
}
};
ContextMenu.prototype.isMenuEnabledByOtherHotInstance = function () {
var hotContainers = $('.handsontable');
var menuEnabled = false;
for(var i = 0, len = hotContainers.length; i < len; i++){
var instance = $(hotContainers[i]).handsontable('getInstance');
if(instance && instance.getSettings().contextMenu){
menuEnabled = true;
break;
}
}
return menuEnabled;
};
ContextMenu.prototype.removeMenu = function () {
if(this.menu.parentNode){
this.menu.parentNode.removeChild(this.menu);
}
}
ContextMenu.prototype.filterItems = function(itemsToLeave){
this.itemsFilter = itemsToLeave;
};
ContextMenu.SEPARATOR = "---------";
function init(){
var instance = this;
var contextMenuSetting = instance.getSettings().contextMenu;
var customOptions = Handsontable.helper.isObject(contextMenuSetting) ? contextMenuSetting : {};
if(contextMenuSetting){
if(!instance.contextMenu){
instance.contextMenu = new ContextMenu(instance, customOptions);
}
instance.contextMenu.enable();
if(Handsontable.helper.isArray(contextMenuSetting)){
instance.contextMenu.filterItems(contextMenuSetting);
}
} else if(instance.contextMenu){
instance.contextMenu.destroy();
delete instance.contextMenu;
}
}
Handsontable.PluginHooks.add('afterInit', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
Handsontable.ContextMenu = ContextMenu;
})(Handsontable);
/**
* This plugin adds support for legacy features, deprecated APIs, etc.
*/
/**
* Support for old autocomplete syntax
* For old syntax, see: https://github.com/warpech/jquery-handsontable/blob/8c9e701d090ea4620fe08b6a1a048672fadf6c7e/README.md#defining-autocomplete
*/
Handsontable.PluginHooks.add('beforeGetCellMeta', function (row, col, cellProperties) {
//isWritable - deprecated since 0.8.0
cellProperties.isWritable = !cellProperties.readOnly;
//autocomplete - deprecated since 0.7.1 (see CHANGELOG.md)
if (cellProperties.autoComplete) {
throw new Error("Support for legacy autocomplete syntax was removed in Handsontable 0.10.0. Please remove the property named 'autoComplete' from your config. For replacement instructions, see wiki page https://github.com/warpech/jquery-handsontable/wiki/Migration-guide-to-0.10.x");
}
});
function HandsontableManualColumnMove() {
var pressed
, startCol
, endCol
, startX
, startOffset;
var ghost = document.createElement('DIV')
, ghostStyle = ghost.style;
ghost.className = 'ghost';
ghostStyle.position = 'absolute';
ghostStyle.top = '25px';
ghostStyle.left = 0;
ghostStyle.width = '10px';
ghostStyle.height = '10px';
ghostStyle.backgroundColor = '#CCC';
ghostStyle.opacity = 0.7;
var saveManualColumnPositions = function () {
var instance = this;
instance.PluginHooks.run('persistentStateSave', 'manualColumnPositions', instance.manualColumnPositions);
};
var loadManualColumnPositions = function () {
var instance = this;
var storedState = {};
instance.PluginHooks.run('persistentStateLoad', 'manualColumnPositions', storedState);
return storedState.value;
};
var bindMoveColEvents = function () {
var instance = this;
instance.rootElement.on('mousemove.manualColumnMove', function (e) {
if (pressed) {
ghostStyle.left = startOffset + e.pageX - startX + 6 + 'px';
if (ghostStyle.display === 'none') {
ghostStyle.display = 'block';
}
}
});
instance.rootElement.on('mouseup.manualColumnMove', function () {
if (pressed) {
if (startCol < endCol) {
endCol--;
}
if (instance.getSettings().rowHeaders) {
startCol--;
endCol--;
}
instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]);
$('.manualColumnMover.active').removeClass('active');
pressed = false;
instance.forceFullRender = true;
instance.view.render(); //updates all
ghostStyle.display = 'none';
saveManualColumnPositions.call(instance);
instance.PluginHooks.run('afterColumnMove', startCol, endCol);
}
});
instance.rootElement.on('mousedown.manualColumnMove', '.manualColumnMover', function (e) {
var mover = e.currentTarget;
var TH = instance.view.wt.wtDom.closest(mover, 'TH');
startCol = instance.view.wt.wtDom.index(TH) + instance.colOffset();
endCol = startCol;
pressed = true;
startX = e.pageX;
var TABLE = instance.$table[0];
TABLE.parentNode.appendChild(ghost);
ghostStyle.width = instance.view.wt.wtDom.outerWidth(TH) + 'px';
ghostStyle.height = instance.view.wt.wtDom.outerHeight(TABLE) + 'px';
startOffset = parseInt(instance.view.wt.wtDom.offset(TH).left - instance.view.wt.wtDom.offset(TABLE).left, 10);
ghostStyle.left = startOffset + 6 + 'px';
});
instance.rootElement.on('mouseenter.manualColumnMove', 'td, th', function () {
if (pressed) {
var active = instance.view.THEAD.querySelector('.manualColumnMover.active');
if (active) {
instance.view.wt.wtDom.removeClass(active, 'active');
}
endCol = instance.view.wt.wtDom.index(this) + instance.colOffset();
var THs = instance.view.THEAD.querySelectorAll('th');
var mover = THs[endCol].querySelector('.manualColumnMover');
instance.view.wt.wtDom.addClass(mover, 'active');
}
});
instance.addHook('afterDestroy', unbindMoveColEvents);
};
var unbindMoveColEvents = function(){
var instance = this;
instance.rootElement.off('mouseup.manualColumnMove');
instance.rootElement.off('mousemove.manualColumnMove');
instance.rootElement.off('mousedown.manualColumnMove');
instance.rootElement.off('mouseenter.manualColumnMove');
};
this.beforeInit = function () {
this.manualColumnPositions = [];
};
this.init = function (source) {
var instance = this;
var manualColMoveEnabled = !!(this.getSettings().manualColumnMove);
if (manualColMoveEnabled) {
var initialManualColumnPositions = this.getSettings().manualColumnMove;
var loadedManualColumnPositions = loadManualColumnPositions.call(instance);
if (typeof loadedManualColumnPositions != 'undefined') {
this.manualColumnPositions = loadedManualColumnPositions;
} else if (initialManualColumnPositions instanceof Array) {
this.manualColumnPositions = initialManualColumnPositions;
} else {
this.manualColumnPositions = [];
}
instance.forceFullRender = true;
if (source == 'afterInit') {
bindMoveColEvents.call(this);
if (this.manualColumnPositions.length > 0) {
this.forceFullRender = true;
this.render();
}
}
} else {
unbindMoveColEvents.call(this);
this.manualColumnPositions = [];
}
};
this.modifyCol = function (col) {
//TODO test performance: http://jsperf.com/object-wrapper-vs-primitive/2
if (this.getSettings().manualColumnMove) {
if (typeof this.manualColumnPositions[col] === 'undefined') {
this.manualColumnPositions[col] = col;
}
return this.manualColumnPositions[col];
}
return col;
};
this.getColHeader = function (col, TH) {
if (this.getSettings().manualColumnMove) {
var DIV = document.createElement('DIV');
DIV.className = 'manualColumnMover';
TH.firstChild.appendChild(DIV);
}
};
}
var htManualColumnMove = new HandsontableManualColumnMove();
Handsontable.PluginHooks.add('beforeInit', htManualColumnMove.beforeInit);
Handsontable.PluginHooks.add('afterInit', function () {
htManualColumnMove.init.call(this, 'afterInit')
});
Handsontable.PluginHooks.add('afterUpdateSettings', function () {
htManualColumnMove.init.call(this, 'afterUpdateSettings')
});
Handsontable.PluginHooks.add('afterGetColHeader', htManualColumnMove.getColHeader);
Handsontable.PluginHooks.add('modifyCol', htManualColumnMove.modifyCol);
function HandsontableManualColumnResize() {
var pressed
, currentTH
, currentCol
, currentWidth
, instance
, newSize
, startX
, startWidth
, startOffset
, resizer = document.createElement('DIV')
, handle = document.createElement('DIV')
, line = document.createElement('DIV')
, lineStyle = line.style;
resizer.className = 'manualColumnResizer';
handle.className = 'manualColumnResizerHandle';
resizer.appendChild(handle);
line.className = 'manualColumnResizerLine';
resizer.appendChild(line);
var $document = $(document);
$document.mousemove(function (e) {
if (pressed) {
currentWidth = startWidth + (e.pageX - startX);
newSize = setManualSize(currentCol, currentWidth); //save col width
resizer.style.left = startOffset + currentWidth + 'px';
}
});
$document.mouseup(function () {
if (pressed) {
instance.view.wt.wtDom.removeClass(resizer, 'active');
pressed = false;
if(newSize != startWidth){
instance.forceFullRender = true;
instance.view.render(); //updates all
saveManualColumnWidths.call(instance);
instance.PluginHooks.run('afterColumnResize', currentCol, newSize);
}
refreshResizerPosition.call(instance, currentTH);
}
});
var saveManualColumnWidths = function () {
var instance = this;
instance.PluginHooks.run('persistentStateSave', 'manualColumnWidths', instance.manualColumnWidths);
};
var loadManualColumnWidths = function () {
var instance = this;
var storedState = {};
instance.PluginHooks.run('persistentStateLoad', 'manualColumnWidths', storedState);
return storedState.value;
};
function refreshResizerPosition(TH) {
instance = this;
currentTH = TH;
var col = this.view.wt.wtTable.getCoords(TH)[1]; //getCoords returns array [row, col]
if (col >= 0) { //if not row header
currentCol = col;
var rootOffset = this.view.wt.wtDom.offset(this.rootElement[0]).left;
var thOffset = this.view.wt.wtDom.offset(TH).left;
startOffset = (thOffset - rootOffset) - 6;
resizer.style.left = startOffset + parseInt(this.view.wt.wtDom.outerWidth(TH), 10) + 'px';
this.rootElement[0].appendChild(resizer);
}
}
function refreshLinePosition() {
var instance = this;
startWidth = parseInt(this.view.wt.wtDom.outerWidth(currentTH), 10);
instance.view.wt.wtDom.addClass(resizer, 'active');
lineStyle.height = instance.view.wt.wtDom.outerHeight(instance.$table[0]) + 'px';
pressed = instance;
}
var bindManualColumnWidthEvents = function () {
var instance = this;
var dblclick = 0;
var autoresizeTimeout = null;
this.rootElement.on('mouseenter.handsontable', 'th', function (e) {
if (!pressed) {
refreshResizerPosition.call(instance, e.currentTarget);
}
});
this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function () {
if (autoresizeTimeout == null) {
autoresizeTimeout = setTimeout(function () {
if (dblclick >= 2) {
newSize = instance.determineColumnWidth.call(instance, currentCol);
setManualSize(currentCol, newSize);
instance.forceFullRender = true;
instance.view.render(); //updates all
instance.PluginHooks.run('afterColumnResize', currentCol, newSize);
}
dblclick = 0;
autoresizeTimeout = null;
}, 500);
}
dblclick++;
});
this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) {
startX = e.pageX;
refreshLinePosition.call(instance);
newSize = startWidth;
});
};
this.beforeInit = function () {
this.manualColumnWidths = [];
};
this.init = function (source) {
var instance = this;
var manualColumnWidthEnabled = !!(this.getSettings().manualColumnResize);
if (manualColumnWidthEnabled) {
var initialColumnWidths = this.getSettings().manualColumnResize;
var loadedManualColumnWidths = loadManualColumnWidths.call(instance);
if (typeof loadedManualColumnWidths != 'undefined') {
this.manualColumnWidths = loadedManualColumnWidths;
} else if (initialColumnWidths instanceof Array) {
this.manualColumnWidths = initialColumnWidths;
} else {
this.manualColumnWidths = [];
}
if (source == 'afterInit') {
bindManualColumnWidthEvents.call(this);
instance.forceFullRender = true;
instance.render();
}
}
};
var setManualSize = function (col, width) {
width = Math.max(width, 20);
/**
* We need to run col through modifyCol hook, in case the order of displayed columns is different than the order
* in data source. For instance, this order can be modified by manualColumnMove plugin.
*/
col = instance.PluginHooks.execute('modifyCol', col);
instance.manualColumnWidths[col] = width;
return width;
};
this.getColWidth = function (col, response) {
if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) {
response.width = this.manualColumnWidths[col];
}
};
}
var htManualColumnResize = new HandsontableManualColumnResize();
Handsontable.PluginHooks.add('beforeInit', htManualColumnResize.beforeInit);
Handsontable.PluginHooks.add('afterInit', function () {
htManualColumnResize.init.call(this, 'afterInit')
});
Handsontable.PluginHooks.add('afterUpdateSettings', function () {
htManualColumnResize.init.call(this, 'afterUpdateSettings')
});
Handsontable.PluginHooks.add('afterGetColWidth', htManualColumnResize.getColWidth);
(function HandsontableObserveChanges() {
Handsontable.PluginHooks.add('afterLoadData', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
function init() {
var instance = this;
var pluginEnabled = instance.getSettings().observeChanges;
if (pluginEnabled) {
if(instance.observer) {
destroy.call(instance); //destroy observer for old data object
}
createObserver.call(instance);
bindEvents.call(instance);
} else if (!pluginEnabled){
destroy.call(instance);
}
}
function createObserver(){
var instance = this;
instance.observeChangesActive = true;
instance.pauseObservingChanges = function(){
instance.observeChangesActive = false;
};
instance.resumeObservingChanges = function(){
instance.observeChangesActive = true;
};
instance.observedData = instance.getData();
instance.observer = jsonpatch.observe(instance.observedData, function (patches) {
if(instance.observeChangesActive){
runHookForOperation.call(instance, patches);
instance.render();
}
instance.runHooks('afterChangesObserved');
});
}
function runHookForOperation(rawPatches){
var instance = this;
var patches = cleanPatches(rawPatches);
for(var i = 0, len = patches.length; i < len; i++){
var patch = patches[i];
var parsedPath = parsePath(patch.path);
switch(patch.op){
case 'add':
if(isNaN(parsedPath.col)){
instance.runHooks('afterCreateRow', parsedPath.row);
} else {
instance.runHooks('afterCreateCol', parsedPath.col);
}
break;
case 'remove':
if(isNaN(parsedPath.col)){
instance.runHooks('afterRemoveRow', parsedPath.row, 1);
} else {
instance.runHooks('afterRemoveCol', parsedPath.col, 1);
}
break;
case 'replace':
instance.runHooks('afterChange', [parsedPath.row, parsedPath.col, null, patch.value], 'external');
break;
}
}
function cleanPatches(rawPatches){
var patches;
patches = removeLengthRelatedPatches(rawPatches);
patches = removeMultipleAddOrRemoveColPatches(patches);
return patches;
}
/**
* Removing or adding column will produce one patch for each table row.
* This function leaves only one patch for each column add/remove operation
*/
function removeMultipleAddOrRemoveColPatches(rawPatches){
var newOrRemovedColumns = [];
return rawPatches.filter(function(patch){
var parsedPath = parsePath(patch.path);
if(['add', 'remove'].indexOf(patch.op) != -1 && !isNaN(parsedPath.col)){
if(newOrRemovedColumns.indexOf(parsedPath.col) != -1){
return false;
} else {
newOrRemovedColumns.push(parsedPath.col);
}
}
return true;
});
}
/**
* If observeChanges uses native Object.observe method, then it produces patches for length property.
* This function removes them.
*/
function removeLengthRelatedPatches(rawPatches){
return rawPatches.filter(function(patch){
return !/[/]length/ig.test(patch.path);
})
}
function parsePath(path){
var match = path.match(/^\/(\d+)\/?(.*)?$/);
return {
row: parseInt(match[1], 10),
col: /^\d*$/.test(match[2]) ? parseInt(match[2], 10) : match[2]
}
}
}
function destroy(){
var instance = this;
if (instance.observer){
destroyObserver.call(instance);
unbindEvents.call(instance);
}
}
function destroyObserver(){
var instance = this;
jsonpatch.unobserve(instance.observedData, instance.observer);
delete instance.observeChangesActive;
delete instance.pauseObservingChanges;
delete instance.resumeObservingChanges;
}
function bindEvents(){
var instance = this;
instance.addHook('afterDestroy', destroy);
instance.addHook('afterCreateRow', afterTableAlter);
instance.addHook('afterRemoveRow', afterTableAlter);
instance.addHook('afterCreateCol', afterTableAlter);
instance.addHook('afterRemoveCol', afterTableAlter);
instance.addHook('afterChange', function(changes, source){
if(source != 'loadData'){
afterTableAlter.call(this);
}
});
}
function unbindEvents(){
var instance = this;
instance.removeHook('afterDestroy', destroy);
instance.removeHook('afterCreateRow', afterTableAlter);
instance.removeHook('afterRemoveRow', afterTableAlter);
instance.removeHook('afterCreateCol', afterTableAlter);
instance.removeHook('afterRemoveCol', afterTableAlter);
instance.removeHook('afterChange', afterTableAlter);
}
function afterTableAlter(){
var instance = this;
instance.pauseObservingChanges();
instance.addHookOnce('afterChangesObserved', function(){
instance.resumeObservingChanges();
});
}
})();
/*
*
* Plugin enables saving table state
*
* */
function Storage(prefix) {
var savedKeys;
var saveSavedKeys = function () {
window.localStorage[prefix + '__' + 'persistentStateKeys'] = JSON.stringify(savedKeys);
};
var loadSavedKeys = function () {
var keysJSON = window.localStorage[prefix + '__' + 'persistentStateKeys'];
var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0;
savedKeys = keys ? keys : [];
};
var clearSavedKeys = function () {
savedKeys = [];
saveSavedKeys();
};
loadSavedKeys();
this.saveValue = function (key, value) {
window.localStorage[prefix + '_' + key] = JSON.stringify(value);
if (savedKeys.indexOf(key) == -1) {
savedKeys.push(key);
saveSavedKeys();
}
};
this.loadValue = function (key, defaultValue) {
key = typeof key != 'undefined' ? key : defaultValue;
var value = window.localStorage[prefix + '_' + key];
return typeof value == "undefined" ? void 0 : JSON.parse(value);
};
this.reset = function (key) {
window.localStorage.removeItem(prefix + '_' + key);
};
this.resetAll = function () {
for (var index = 0; index < savedKeys.length; index++) {
window.localStorage.removeItem(prefix + '_' + savedKeys[index]);
}
clearSavedKeys();
};
}
(function (StorageClass) {
function HandsontablePersistentState() {
var plugin = this;
this.init = function () {
var instance = this,
pluginSettings = instance.getSettings()['persistentState'];
plugin.enabled = !!(pluginSettings);
if (!plugin.enabled) {
removeHooks.call(instance);
return;
}
if (!instance.storage) {
instance.storage = new StorageClass(instance.rootElement[0].id);
}
instance.resetState = plugin.resetValue;
addHooks.call(instance);
};
this.saveValue = function (key, value) {
var instance = this;
instance.storage.saveValue(key, value);
};
this.loadValue = function (key, saveTo) {
var instance = this;
saveTo.value = instance.storage.loadValue(key);
};
this.resetValue = function (key) {
var instance = this;
if (typeof key != 'undefined') {
instance.storage.reset(key);
} else {
instance.storage.resetAll();
}
};
var hooks = {
'persistentStateSave': plugin.saveValue,
'persistentStateLoad': plugin.loadValue,
'persistentStateReset': plugin.resetValue
};
function addHooks() {
var instance = this;
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName) && !hookExists.call(instance, hookName)) {
instance.PluginHooks.add(hookName, hooks[hookName]);
}
}
}
function removeHooks() {
var instance = this;
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName) && hookExists.call(instance, hookName)) {
instance.PluginHooks.remove(hookName, hooks[hookName]);
}
}
}
function hookExists(hookName) {
var instance = this;
return instance.PluginHooks.hooks.hasOwnProperty(hookName);
}
}
var htPersistentState = new HandsontablePersistentState();
Handsontable.PluginHooks.add('beforeInit', htPersistentState.init);
Handsontable.PluginHooks.add('afterUpdateSettings', htPersistentState.init);
})(Storage);
/**
* Handsontable UndoRedo class
*/
(function(Handsontable){
Handsontable.UndoRedo = function (instance) {
var plugin = this;
this.instance = instance;
this.doneActions = [];
this.undoneActions = [];
this.ignoreNewActions = false;
instance.addHook("afterChange", function (changes, origin) {
if(changes){
var action = new Handsontable.UndoRedo.ChangeAction(changes);
plugin.done(action);
}
});
instance.addHook("afterCreateRow", function (index, amount, createdAutomatically) {
if (createdAutomatically) {
return;
}
var action = new Handsontable.UndoRedo.CreateRowAction(index, amount);
plugin.done(action);
});
instance.addHook("beforeRemoveRow", function (index, amount) {
var originalData = plugin.instance.getData();
index = ( originalData.length + index ) % originalData.length;
var removedData = originalData.slice(index, index + amount);
var action = new Handsontable.UndoRedo.RemoveRowAction(index, removedData);
plugin.done(action);
});
instance.addHook("afterCreateCol", function (index, amount, createdAutomatically) {
if (createdAutomatically) {
return;
}
var action = new Handsontable.UndoRedo.CreateColumnAction(index, amount);
plugin.done(action);
});
instance.addHook("beforeRemoveCol", function (index, amount) {
var originalData = plugin.instance.getData();
index = ( plugin.instance.countCols() + index ) % plugin.instance.countCols();
var removedData = [];
for (var i = 0, len = originalData.length; i < len; i++) {
removedData[i] = originalData[i].slice(index, index + amount);
}
var headers;
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
headers = instance.getSettings().colHeaders.slice(index, index + removedData.length);
}
var action = new Handsontable.UndoRedo.RemoveColumnAction(index, removedData, headers);
plugin.done(action);
});
};
Handsontable.UndoRedo.prototype.done = function (action) {
if (!this.ignoreNewActions) {
this.doneActions.push(action);
this.undoneActions.length = 0;
}
};
/**
* Undo operation from current revision
*/
Handsontable.UndoRedo.prototype.undo = function () {
if (this.isUndoAvailable()) {
var action = this.doneActions.pop();
this.ignoreNewActions = true;
action.undo(this.instance);
this.ignoreNewActions = false;
this.undoneActions.push(action);
}
};
/**
* Redo operation from current revision
*/
Handsontable.UndoRedo.prototype.redo = function () {
if (this.isRedoAvailable()) {
var action = this.undoneActions.pop();
this.ignoreNewActions = true;
action.redo(this.instance);
this.ignoreNewActions = true;
this.doneActions.push(action);
}
};
/**
* Returns true if undo point is available
* @return {Boolean}
*/
Handsontable.UndoRedo.prototype.isUndoAvailable = function () {
return this.doneActions.length > 0;
};
/**
* Returns true if redo point is available
* @return {Boolean}
*/
Handsontable.UndoRedo.prototype.isRedoAvailable = function () {
return this.undoneActions.length > 0;
};
/**
* Clears undo history
*/
Handsontable.UndoRedo.prototype.clear = function () {
this.doneActions.length = 0;
this.undoneActions.length = 0;
};
Handsontable.UndoRedo.Action = function () {
};
Handsontable.UndoRedo.Action.prototype.undo = function () {
};
Handsontable.UndoRedo.Action.prototype.redo = function () {
};
Handsontable.UndoRedo.ChangeAction = function (changes) {
this.changes = changes;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.ChangeAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.ChangeAction.prototype.undo = function (instance) {
var data = $.extend(true, [], this.changes);
for (var i = 0, len = data.length; i < len; i++) {
data[i].splice(3, 1);
}
instance.setDataAtRowProp(data, null, null, 'undo');
};
Handsontable.UndoRedo.ChangeAction.prototype.redo = function (instance) {
var data = $.extend(true, [], this.changes);
for (var i = 0, len = data.length; i < len; i++) {
data[i].splice(2, 1);
}
instance.setDataAtRowProp(data, null, null, 'redo');
};
Handsontable.UndoRedo.CreateRowAction = function (index, amount) {
this.index = index;
this.amount = amount;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.CreateRowAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.CreateRowAction.prototype.undo = function (instance) {
instance.alter('remove_row', this.index, this.amount);
};
Handsontable.UndoRedo.CreateRowAction.prototype.redo = function (instance) {
instance.alter('insert_row', this.index + 1, this.amount);
};
Handsontable.UndoRedo.RemoveRowAction = function (index, data) {
this.index = index;
this.data = data;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveRowAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.RemoveRowAction.prototype.undo = function (instance) {
var spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.data);
Array.prototype.splice.apply(instance.getData(), spliceArgs);
instance.render();
};
Handsontable.UndoRedo.RemoveRowAction.prototype.redo = function (instance) {
instance.alter('remove_row', this.index, this.data.length);
};
Handsontable.UndoRedo.CreateColumnAction = function (index, amount) {
this.index = index;
this.amount = amount;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.CreateColumnAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.CreateColumnAction.prototype.undo = function (instance) {
instance.alter('remove_col', this.index, this.amount);
};
Handsontable.UndoRedo.CreateColumnAction.prototype.redo = function (instance) {
instance.alter('insert_col', this.index + 1, this.amount);
};
Handsontable.UndoRedo.RemoveColumnAction = function (index, data, headers) {
this.index = index;
this.data = data;
this.amount = this.data[0].length;
this.headers = headers;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveColumnAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.RemoveColumnAction.prototype.undo = function (instance) {
var row, spliceArgs;
for (var i = 0, len = instance.getData().length; i < len; i++) {
row = instance.getDataAtRow(i);
spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.data[i]);
Array.prototype.splice.apply(row, spliceArgs);
}
if(typeof this.headers != 'undefined'){
spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.headers);
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArgs);
}
instance.render();
};
Handsontable.UndoRedo.RemoveColumnAction.prototype.redo = function (instance) {
instance.alter('remove_col', this.index, this.amount);
};
})(Handsontable);
(function(Handsontable){
function init(){
var instance = this;
var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo;
if(pluginEnabled){
if(!instance.undoRedo){
instance.undoRedo = new Handsontable.UndoRedo(instance);
exposeUndoRedoMethods(instance);
instance.addHook('beforeKeyDown', onBeforeKeyDown);
instance.addHook('afterChange', onAfterChange);
}
} else {
if(instance.undoRedo){
delete instance.undoRedo;
removeExposedUndoRedoMethods(instance);
instance.removeHook('beforeKeyDown', onBeforeKeyDown);
instance.removeHook('afterChange', onAfterChange);
}
}
}
function onBeforeKeyDown(event){
var instance = this;
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;
if(ctrlDown){
if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { //CTRL + Y or CTRL + SHIFT + Z
instance.undoRedo.redo();
event.stopImmediatePropagation();
}
else if (event.keyCode === 90) { //CTRL + Z
instance.undoRedo.undo();
event.stopImmediatePropagation();
}
}
}
function onAfterChange(changes, source){
var instance = this;
if (source == 'loadData'){
return instance.undoRedo.clear();
}
}
function exposeUndoRedoMethods(instance){
instance.undo = function(){
return instance.undoRedo.undo();
};
instance.redo = function(){
return instance.undoRedo.redo();
};
instance.isUndoAvailable = function(){
return instance.undoRedo.isUndoAvailable();
};
instance.isRedoAvailable = function(){
return instance.undoRedo.isRedoAvailable();
};
instance.clearUndo = function(){
return instance.undoRedo.clear();
};
}
function removeExposedUndoRedoMethods(instance){
delete instance.undo;
delete instance.redo;
delete instance.isUndoAvailable;
delete instance.isRedoAvailable;
delete instance.clearUndo;
}
Handsontable.PluginHooks.add('afterInit', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
})(Handsontable);
/**
* Plugin used to scroll Handsontable by selecting a cell and dragging outside of visible viewport
* @constructor
*/
function DragToScroll() {
this.boundaries = null;
this.callback = null;
}
/**
* @param boundaries {Object} compatible with getBoundingClientRect
*/
DragToScroll.prototype.setBoundaries = function (boundaries) {
this.boundaries = boundaries;
};
/**
* @param callback {Function}
*/
DragToScroll.prototype.setCallback = function (callback) {
this.callback = callback;
};
/**
* Check if mouse position (x, y) is outside of the viewport
* @param x
* @param y
*/
DragToScroll.prototype.check = function (x, y) {
var diffX = 0;
var diffY = 0;
if (y < this.boundaries.top) {
//y is less than top
diffY = y - this.boundaries.top;
}
else if (y > this.boundaries.bottom) {
//y is more than bottom
diffY = y - this.boundaries.bottom;
}
if (x < this.boundaries.left) {
//x is less than left
diffX = x - this.boundaries.left;
}
else if (x > this.boundaries.right) {
//x is more than right
diffX = x - this.boundaries.right;
}
this.callback(diffX, diffY);
};
var listening = false;
var dragToScroll;
var instance;
if (typeof Handsontable !== 'undefined') {
var setupListening = function (instance) {
var scrollHandler = instance.view.wt.wtScrollbars.vertical.scrollHandler; //native scroll
dragToScroll = new DragToScroll();
if (scrollHandler === window) {
//not much we can do currently
return;
}
else if (scrollHandler) {
dragToScroll.setBoundaries(scrollHandler.getBoundingClientRect());
}
else {
dragToScroll.setBoundaries(instance.$table[0].getBoundingClientRect());
}
dragToScroll.setCallback(function (scrollX, scrollY) {
if (scrollX < 0) {
if (scrollHandler) {
scrollHandler.scrollLeft -= 50;
}
else {
instance.view.wt.scrollHorizontal(-1).draw();
}
}
else if (scrollX > 0) {
if (scrollHandler) {
scrollHandler.scrollLeft += 50;
}
else {
instance.view.wt.scrollHorizontal(1).draw();
}
}
if (scrollY < 0) {
if (scrollHandler) {
scrollHandler.scrollTop -= 20;
}
else {
instance.view.wt.scrollVertical(-1).draw();
}
}
else if (scrollY > 0) {
if (scrollHandler) {
scrollHandler.scrollTop += 20;
}
else {
instance.view.wt.scrollVertical(1).draw();
}
}
});
listening = true;
};
Handsontable.PluginHooks.add('afterInit', function () {
$(document).on('mouseup.' + this.guid, function () {
listening = false;
});
$(document).on('mousemove.' + this.guid, function (event) {
if (listening) {
dragToScroll.check(event.clientX, event.clientY);
}
});
});
Handsontable.PluginHooks.add('destroy', function () {
$(document).off('.' + this.guid);
});
Handsontable.PluginHooks.add('afterOnCellMouseDown', function () {
setupListening(this);
});
Handsontable.PluginHooks.add('afterOnCellCornerMouseDown', function () {
setupListening(this);
});
}
(function (Handsontable, CopyPaste, SheetClip) {
function CopyPastePlugin(instance) {
this.copyPasteInstance = CopyPaste.getInstance();
this.copyPasteInstance.onCut(onCut);
this.copyPasteInstance.onPaste(onPaste);
var plugin = this;
instance.addHook('beforeKeyDown', onBeforeKeyDown);
function onCut() {
if (!instance.isListening()) {
return;
}
instance.selection.empty();
}
function onPaste(str) {
if (!instance.isListening() || !instance.selection.isSelected()) {
return;
}
var input = str.replace(/^[\r\n]*/g, '').replace(/[\r\n]*$/g, '') //remove newline from the start and the end of the input
, inputArray = SheetClip.parse(input)
, selected = instance.getSelected()
, coords = instance.getCornerCoords([{row: selected[0], col: selected[1]}, {row: selected[2], col: selected[3]}])
, areaStart = coords.TL
, areaEnd = {
row: Math.max(coords.BR.row, inputArray.length - 1 + coords.TL.row),
col: Math.max(coords.BR.col, inputArray[0].length - 1 + coords.TL.col)
};
instance.PluginHooks.once('afterChange', function (changes, source) {
if (changes && changes.length) {
this.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col);
}
});
instance.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'paste', instance.getSettings().pasteMode);
};
function onBeforeKeyDown (event) {
if (Handsontable.helper.isCtrlKey(event.keyCode) && instance.getSelected()) {
//when CTRL is pressed, prepare selectable text in textarea
//http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript
plugin.setCopyableText();
event.stopImmediatePropagation();
return;
}
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
if (event.keyCode == Handsontable.helper.keyCode.A && ctrlDown) {
setTimeout(Handsontable.helper.proxy(plugin.setCopyableText, plugin));
}
}
this.destroy = function () {
this.copyPasteInstance.removeCallback(onCut);
this.copyPasteInstance.removeCallback(onPaste);
this.copyPasteInstance.destroy();
instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
instance.addHook('afterDestroy', Handsontable.helper.proxy(this.destroy, this));
this.triggerPaste = Handsontable.helper.proxy(this.copyPasteInstance.triggerPaste, this.copyPasteInstance);
this.triggerCut = Handsontable.helper.proxy(this.copyPasteInstance.triggerCut, this.copyPasteInstance);
/**
* Prepares copyable text in the invisible textarea
*/
this.setCopyableText = function () {
var selection = instance.getSelected();
var settings = instance.getSettings();
var copyRowsLimit = settings.copyRowsLimit;
var copyColsLimit = settings.copyColsLimit;
var startRow = Math.min(selection[0], selection[2]);
var startCol = Math.min(selection[1], selection[3]);
var endRow = Math.max(selection[0], selection[2]);
var endCol = Math.max(selection[1], selection[3]);
var finalEndRow = Math.min(endRow, startRow + copyRowsLimit - 1);
var finalEndCol = Math.min(endCol, startCol + copyColsLimit - 1);
instance.copyPaste.copyPasteInstance.copyable(instance.getCopyableData(startRow, startCol, finalEndRow, finalEndCol));
if (endRow !== finalEndRow || endCol !== finalEndCol) {
instance.PluginHooks.run("afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, copyRowsLimit, copyColsLimit);
}
};
}
function init() {
var instance = this;
var pluginEnabled = instance.getSettings().copyPaste !== false;
if(pluginEnabled && !instance.copyPaste){
instance.copyPaste = new CopyPastePlugin(instance);
} else if (!pluginEnabled && instance.copyPaste) {
instance.copyPaste.destroy();
delete instance.copyPaste;
}
}
Handsontable.PluginHooks.add('afterInit', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
})(Handsontable, CopyPaste, SheetClip);
/**
* Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable
* and (optionally) implements behavior needed for native horizontal and vertical scrolling
*/
function WalkontableOverlay() {
this.maxOuts = 10; //max outs in one direction (before and after table)
}
/*
Possible optimizations:
[x] don't rerender if scroll delta is smaller than the fragment outside of the viewport
[ ] move .style.top change before .draw()
[ ] put .draw() in requestAnimationFrame
[ ] don't rerender rows that remain visible after the scroll
*/
WalkontableOverlay.prototype.init = function () {
this.TABLE = this.instance.wtTable.TABLE;
this.fixed = this.instance.wtTable.hider;
this.fixedContainer = this.instance.wtTable.holder;
this.fixed.style.position = 'absolute';
this.fixed.style.left = '0';
this.scrollHandler = this.getScrollableElement(this.TABLE);
this.$scrollHandler = $(this.scrollHandler); //in future remove jQuery from here
};
WalkontableOverlay.prototype.makeClone = function (direction) {
var clone = document.createElement('DIV');
clone.className = 'ht_clone_' + direction + ' handsontable';
clone.style.position = 'fixed';
clone.style.overflow = 'hidden';
var table2 = document.createElement('TABLE');
table2.className = this.instance.wtTable.TABLE.className;
clone.appendChild(table2);
this.instance.wtTable.holder.parentNode.appendChild(clone);
return new Walkontable({
cloneSource: this.instance,
cloneOverlay: this,
table: table2
});
};
WalkontableOverlay.prototype.getScrollableElement = function (TABLE) {
var el = TABLE.parentNode;
while (el && el.style) {
if (el.style.overflow !== 'visible' && el.style.overflow !== '') {
return el;
}
if (this instanceof WalkontableHorizontalScrollbarNative && el.style.overflowX !== 'visible' && el.style.overflowX !== '') {
return el;
}
el = el.parentNode;
}
return window;
};
WalkontableOverlay.prototype.prepare = function () {
};
WalkontableOverlay.prototype.onScroll = function (forcePosition) {
this.windowScrollPosition = this.getScrollPosition();
this.readSettings(); //read window scroll position
if (forcePosition) {
this.windowScrollPosition = forcePosition;
}
this.resetFixedPosition(); //may be redundant
};
WalkontableOverlay.prototype.availableSize = function () {
var availableSize;
if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table
if (this.instance.wtTable.getLastVisibleRow() === this.total - 1) {
availableSize = this.instance.wtDom.outerHeight(this.TABLE);
}
else {
availableSize = this.windowSize;
}
}
else {
availableSize = this.windowSize - (this.tableParentOffset);
}
return availableSize;
};
WalkontableOverlay.prototype.refresh = function (selectionsOnly) {
var last = this.getLastCell();
this.measureBefore = this.sumCellSizes(0, this.offset);
if (last === -1) { //last -1 means that viewport is scrolled behind the table
this.measureAfter = 0;
}
else {
this.measureAfter = this.sumCellSizes(last, this.total - last);
}
this.applyToDOM();
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableOverlay.prototype.destroy = function () {
this.$scrollHandler.off('.' + this.instance.guid);
$(window).off('.' + this.instance.guid);
$(document).off('.' + this.instance.guid);
};
function WalkontableBorder(instance, settings) {
var style;
//reference to instance
this.instance = instance;
this.settings = settings;
this.wtDom = this.instance.wtDom;
this.main = document.createElement("div");
style = this.main.style;
style.position = 'absolute';
style.top = 0;
style.left = 0;
// style.visibility = 'hidden';
for (var i = 0; i < 5; i++) {
var DIV = document.createElement('DIV');
DIV.className = 'wtBorder ' + (settings.className || '');
style = DIV.style;
style.backgroundColor = settings.border.color;
style.height = settings.border.width + 'px';
style.width = settings.border.width + 'px';
this.main.appendChild(DIV);
}
this.top = this.main.childNodes[0];
this.left = this.main.childNodes[1];
this.bottom = this.main.childNodes[2];
this.right = this.main.childNodes[3];
/*$(this.top).on(sss, function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$(this).hide();
});
$(this.left).on(sss, function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$(this).hide();
});
$(this.bottom).on(sss, function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$(this).hide();
});
$(this.right).on(sss, function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$(this).hide();
});*/
this.topStyle = this.top.style;
this.leftStyle = this.left.style;
this.bottomStyle = this.bottom.style;
this.rightStyle = this.right.style;
this.corner = this.main.childNodes[4];
this.corner.className += ' corner';
this.cornerStyle = this.corner.style;
this.cornerStyle.width = '5px';
this.cornerStyle.height = '5px';
this.cornerStyle.border = '2px solid #FFF';
this.disappear();
if (!instance.wtTable.bordersHolder) {
instance.wtTable.bordersHolder = document.createElement('div');
instance.wtTable.bordersHolder.className = 'htBorders';
instance.wtTable.hider.appendChild(instance.wtTable.bordersHolder);
}
instance.wtTable.bordersHolder.appendChild(this.main);
var down = false;
var $body = $(document.body);
$body.on('mousedown.walkontable.' + instance.guid, function () {
down = true;
});
$body.on('mouseup.walkontable.' + instance.guid, function () {
down = false
});
$(this.main.childNodes).on('mouseenter', function (event) {
if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) {
return;
}
event.preventDefault();
event.stopImmediatePropagation();
var bounds = this.getBoundingClientRect();
var $this = $(this);
$this.hide();
var isOutside = function (event) {
if (event.clientY < Math.floor(bounds.top)) {
return true;
}
if (event.clientY > Math.ceil(bounds.top + bounds.height)) {
return true;
}
if (event.clientX < Math.floor(bounds.left)) {
return true;
}
if (event.clientX > Math.ceil(bounds.left + bounds.width)) {
return true;
}
};
$body.on('mousemove.border.' + instance.guid, function (event) {
if (isOutside(event)) {
$body.off('mousemove.border.' + instance.guid);
$this.show();
}
});
});
}
/**
* Show border around one or many cells
* @param {Array} corners
*/
WalkontableBorder.prototype.appear = function (corners) {
var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width;
if (this.disabled) {
return;
}
var instance = this.instance
, fromRow
, fromColumn
, toRow
, toColumn
, hideTop = false
, hideLeft = false
, hideBottom = false
, hideRight = false
, i
, ilen
, s;
if (!instance.wtTable.isRowInViewport(corners[0])) {
hideTop = true;
}
if (!instance.wtTable.isRowInViewport(corners[2])) {
hideBottom = true;
}
ilen = instance.wtTable.rowStrategy.countVisible();
for (i = 0; i < ilen; i++) {
s = instance.wtTable.rowFilter.visibleToSource(i);
if (s >= corners[0] && s <= corners[2]) {
fromRow = s;
break;
}
}
for (i = ilen - 1; i >= 0; i--) {
s = instance.wtTable.rowFilter.visibleToSource(i);
if (s >= corners[0] && s <= corners[2]) {
toRow = s;
break;
}
}
if (hideTop && hideBottom) {
hideLeft = true;
hideRight = true;
}
else {
if (!instance.wtTable.isColumnInViewport(corners[1])) {
hideLeft = true;
}
if (!instance.wtTable.isColumnInViewport(corners[3])) {
hideRight = true;
}
ilen = instance.wtTable.columnStrategy.countVisible();
for (i = 0; i < ilen; i++) {
s = instance.wtTable.columnFilter.visibleToSource(i);
if (s >= corners[1] && s <= corners[3]) {
fromColumn = s;
break;
}
}
for (i = ilen - 1; i >= 0; i--) {
s = instance.wtTable.columnFilter.visibleToSource(i);
if (s >= corners[1] && s <= corners[3]) {
toColumn = s;
break;
}
}
}
if (fromRow !== void 0 && fromColumn !== void 0) {
isMultiple = (fromRow !== toRow || fromColumn !== toColumn);
fromTD = instance.wtTable.getCell([fromRow, fromColumn]);
toTD = isMultiple ? instance.wtTable.getCell([toRow, toColumn]) : fromTD;
fromOffset = this.wtDom.offset(fromTD);
toOffset = isMultiple ? this.wtDom.offset(toTD) : fromOffset;
containerOffset = this.wtDom.offset(instance.wtTable.TABLE);
minTop = fromOffset.top;
height = toOffset.top + this.wtDom.outerHeight(toTD) - minTop;
minLeft = fromOffset.left;
width = toOffset.left + this.wtDom.outerWidth(toTD) - minLeft;
top = minTop - containerOffset.top - 1;
left = minLeft - containerOffset.left - 1;
var style = this.wtDom.getComputedStyle(fromTD);
if (parseInt(style['borderTopWidth'], 10) > 0) {
top += 1;
height = height > 0 ? height - 1 : 0;
}
if (parseInt(style['borderLeftWidth'], 10) > 0) {
left += 1;
width = width > 0 ? width - 1 : 0;
}
}
else {
this.disappear();
return;
}
if (hideTop) {
this.topStyle.display = 'none';
}
else {
this.topStyle.top = top + 'px';
this.topStyle.left = left + 'px';
this.topStyle.width = width + 'px';
this.topStyle.display = 'block';
}
if (hideLeft) {
this.leftStyle.display = 'none';
}
else {
this.leftStyle.top = top + 'px';
this.leftStyle.left = left + 'px';
this.leftStyle.height = height + 'px';
this.leftStyle.display = 'block';
}
var delta = Math.floor(this.settings.border.width / 2);
if (hideBottom) {
this.bottomStyle.display = 'none';
}
else {
this.bottomStyle.top = top + height - delta + 'px';
this.bottomStyle.left = left + 'px';
this.bottomStyle.width = width + 'px';
this.bottomStyle.display = 'block';
}
if (hideRight) {
this.rightStyle.display = 'none';
}
else {
this.rightStyle.top = top + 'px';
this.rightStyle.left = left + width - delta + 'px';
this.rightStyle.height = height + 1 + 'px';
this.rightStyle.display = 'block';
}
if (hideBottom || hideRight || !this.hasSetting(this.settings.border.cornerVisible)) {
this.cornerStyle.display = 'none';
}
else {
this.cornerStyle.top = top + height - 4 + 'px';
this.cornerStyle.left = left + width - 4 + 'px';
this.cornerStyle.display = 'block';
}
};
/**
* Hide border
*/
WalkontableBorder.prototype.disappear = function () {
this.topStyle.display = 'none';
this.leftStyle.display = 'none';
this.bottomStyle.display = 'none';
this.rightStyle.display = 'none';
this.cornerStyle.display = 'none';
};
WalkontableBorder.prototype.hasSetting = function (setting) {
if (typeof setting === 'function') {
return setting();
}
return !!setting;
};
/**
* WalkontableCellFilter
* @constructor
*/
function WalkontableCellFilter() {
this.offset = 0;
this.total = 0;
this.fixedCount = 0;
}
WalkontableCellFilter.prototype.source = function (n) {
return n;
};
WalkontableCellFilter.prototype.offsetted = function (n) {
return n + this.offset;
};
WalkontableCellFilter.prototype.unOffsetted = function (n) {
return n - this.offset;
};
WalkontableCellFilter.prototype.fixed = function (n) {
if (n < this.fixedCount) {
return n - this.offset;
}
else {
return n;
}
};
WalkontableCellFilter.prototype.unFixed = function (n) {
if (n < this.fixedCount) {
return n + this.offset;
}
else {
return n;
}
};
WalkontableCellFilter.prototype.visibleToSource = function (n) {
return this.source(this.offsetted(this.fixed(n)));
};
WalkontableCellFilter.prototype.sourceToVisible = function (n) {
return this.source(this.unOffsetted(this.unFixed(n)));
};
/**
* WalkontableCellStrategy
* @constructor
*/
function WalkontableCellStrategy(instance) {
this.instance = instance;
}
WalkontableCellStrategy.prototype.getSize = function (index) {
return this.cellSizes[index];
};
WalkontableCellStrategy.prototype.getContainerSize = function (proposedSize) {
return typeof this.containerSizeFn === 'function' ? this.containerSizeFn(proposedSize) : this.containerSizeFn;
};
WalkontableCellStrategy.prototype.countVisible = function () {
return this.cellCount;
};
WalkontableCellStrategy.prototype.isLastIncomplete = function () {
if(this.instance.getSetting('nativeScrollbars')){
var nativeScrollbar = this.instance.cloneFrom ? this.instance.cloneFrom.wtScrollbars.vertical : this.instance.wtScrollbars.vertical;
return this.remainingSize > nativeScrollbar.sumCellSizes(nativeScrollbar.offset, nativeScrollbar.offset + nativeScrollbar.curOuts + 1);
} else {
return this.remainingSize > 0;
}
};
/**
* WalkontableClassNameList
* @constructor
*/
function WalkontableClassNameCache() {
this.cache = [];
}
WalkontableClassNameCache.prototype.add = function (r, c, cls) {
if (!this.cache[r]) {
this.cache[r] = [];
}
if (!this.cache[r][c]) {
this.cache[r][c] = [];
}
this.cache[r][c][cls] = true;
};
WalkontableClassNameCache.prototype.test = function (r, c, cls) {
return (this.cache[r] && this.cache[r][c] && this.cache[r][c][cls]);
};
/**
* WalkontableColumnFilter
* @constructor
*/
function WalkontableColumnFilter() {
this.countTH = 0;
}
WalkontableColumnFilter.prototype = new WalkontableCellFilter();
WalkontableColumnFilter.prototype.readSettings = function (instance) {
this.offset = instance.wtSettings.settings.offsetColumn;
this.total = instance.getSetting('totalColumns');
this.fixedCount = instance.getSetting('fixedColumnsLeft');
this.countTH = instance.getSetting('rowHeaders').length;
};
WalkontableColumnFilter.prototype.offsettedTH = function (n) {
return n - this.countTH;
};
WalkontableColumnFilter.prototype.unOffsettedTH = function (n) {
return n + this.countTH;
};
WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function (n) {
return this.visibleToSource(this.offsettedTH(n));
};
WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function (n) {
return this.unOffsettedTH(this.sourceToVisible(n));
};
/**
* WalkontableColumnStrategy
* @param containerSizeFn
* @param sizeAtIndex
* @param strategy - all, last, none
* @constructor
*/
function WalkontableColumnStrategy(instance, containerSizeFn, sizeAtIndex, strategy) {
var size
, i = 0;
WalkontableCellStrategy.apply(this, arguments);
this.containerSizeFn = containerSizeFn;
this.cellSizesSum = 0;
this.cellSizes = [];
this.cellStretch = [];
this.cellCount = 0;
this.remainingSize = 0;
this.strategy = strategy;
//step 1 - determine cells that fit containerSize and cache their widths
while (true) {
size = sizeAtIndex(i);
if (size === void 0) {
break; //total columns exceeded
}
if (this.cellSizesSum >= this.getContainerSize(this.cellSizesSum + size)) {
break; //total width exceeded
}
this.cellSizes.push(size);
this.cellSizesSum += size;
this.cellCount++;
i++;
}
var containerSize = this.getContainerSize(this.cellSizesSum);
this.remainingSize = this.cellSizesSum - containerSize;
//negative value means the last cell is fully visible and there is some space left for stretching
//positive value means the last cell is not fully visible
}
WalkontableColumnStrategy.prototype = new WalkontableCellStrategy();
WalkontableColumnStrategy.prototype.getSize = function (index) {
return this.cellSizes[index] + (this.cellStretch[index] || 0);
};
WalkontableColumnStrategy.prototype.stretch = function () {
//step 2 - apply stretching strategy
var containerSize = this.getContainerSize(this.cellSizesSum)
, i = 0;
this.remainingSize = this.cellSizesSum - containerSize;
this.cellStretch.length = 0; //clear previous stretch
if (this.strategy === 'all') {
if (this.remainingSize < 0) {
var ratio = containerSize / this.cellSizesSum;
var newSize;
while (i < this.cellCount - 1) { //"i < this.cellCount - 1" is needed because last cellSize is adjusted after the loop
newSize = Math.floor(ratio * this.cellSizes[i]);
this.remainingSize += newSize - this.cellSizes[i];
this.cellStretch[i] = newSize - this.cellSizes[i];
i++;
}
this.cellStretch[this.cellCount - 1] = -this.remainingSize;
this.remainingSize = 0;
}
}
else if (this.strategy === 'last') {
if (this.remainingSize < 0 && containerSize !== Infinity) { //Infinity is with native scroll when the table is wider than the viewport (TODO: test)
this.cellStretch[this.cellCount - 1] = -this.remainingSize;
this.remainingSize = 0;
}
}
};
function Walkontable(settings) {
var that = this,
originalHeaders = [];
this.guid = 'wt_' + walkontableRandomString(); //this is the namespace for global events
//bootstrap from settings
this.wtDom = new WalkontableDom();
if (settings.cloneSource) {
this.cloneSource = settings.cloneSource;
this.cloneOverlay = settings.cloneOverlay;
this.wtSettings = settings.cloneSource.wtSettings;
this.wtTable = new WalkontableTable(this, settings.table);
this.wtScroll = new WalkontableScroll(this);
this.wtViewport = settings.cloneSource.wtViewport;
}
else {
this.wtSettings = new WalkontableSettings(this, settings);
this.wtTable = new WalkontableTable(this, settings.table);
this.wtScroll = new WalkontableScroll(this);
this.wtViewport = new WalkontableViewport(this);
this.wtScrollbars = new WalkontableScrollbars(this);
this.wtWheel = new WalkontableWheel(this);
this.wtEvent = new WalkontableEvent(this);
}
//find original headers
if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) {
for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) {
originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML);
}
if (!this.getSetting('columnHeaders').length) {
this.update('columnHeaders', [function (column, TH) {
that.wtDom.fastInnerText(TH, originalHeaders[column]);
}]);
}
}
//initialize selections
this.selections = {};
var selectionsSettings = this.getSetting('selections');
if (selectionsSettings) {
for (var i in selectionsSettings) {
if (selectionsSettings.hasOwnProperty(i)) {
this.selections[i] = new WalkontableSelection(this, selectionsSettings[i]);
}
}
}
this.drawn = false;
this.drawInterrupted = false;
//at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table
/*if (window.Handsontable) {
Handsontable.PluginHooks.add('beforeChange', function () {
if (that.rowHeightCache) {
that.rowHeightCache.length = 0;
}
});
}*/
}
Walkontable.prototype.draw = function (selectionsOnly) {
this.drawInterrupted = false;
if (!selectionsOnly && !this.wtDom.isVisible(this.wtTable.TABLE)) {
this.drawInterrupted = true; //draw interrupted because TABLE is not visible
return;
}
this.getSetting('beforeDraw', !selectionsOnly);
selectionsOnly = selectionsOnly && this.getSetting('offsetRow') === this.lastOffsetRow && this.getSetting('offsetColumn') === this.lastOffsetColumn;
if (this.drawn) { //fix offsets that might have changed
this.scrollVertical(0);
this.scrollHorizontal(0);
}
this.lastOffsetRow = this.getSetting('offsetRow');
this.lastOffsetColumn = this.getSetting('offsetColumn');
this.wtTable.draw(selectionsOnly);
if (!this.cloneSource) {
this.getSetting('onDraw', !selectionsOnly);
}
return this;
};
Walkontable.prototype.update = function (settings, value) {
return this.wtSettings.update(settings, value);
};
Walkontable.prototype.scrollVertical = function (delta) {
var result = this.wtScroll.scrollVertical(delta);
this.getSetting('onScrollVertically');
return result;
};
Walkontable.prototype.scrollHorizontal = function (delta) {
var result = this.wtScroll.scrollHorizontal(delta);
this.getSetting('onScrollHorizontally');
return result;
};
Walkontable.prototype.scrollViewport = function (coords) {
this.wtScroll.scrollViewport(coords);
return this;
};
Walkontable.prototype.getViewport = function () {
return [
this.wtTable.rowFilter.visibleToSource(0),
this.wtTable.columnFilter.visibleToSource(0),
this.wtTable.getLastVisibleRow(),
this.wtTable.getLastVisibleColumn()
];
};
Walkontable.prototype.getSetting = function (key, param1, param2, param3) {
return this.wtSettings.getSetting(key, param1, param2, param3);
};
Walkontable.prototype.hasSetting = function (key) {
return this.wtSettings.has(key);
};
Walkontable.prototype.destroy = function () {
$(document.body).off('.' + this.guid);
this.wtScrollbars.destroy();
clearTimeout(this.wheelTimeout);
this.wtEvent && this.wtEvent.destroy();
};
/**
* A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays.
* Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly
* @param instance
* @constructor
*/
function WalkontableDebugOverlay(instance) {
this.instance = instance;
this.init();
this.clone = this.makeClone('debug');
this.clone.wtTable.holder.style.opacity = 0.4;
this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000';
var that = this;
var lastTimeout;
var lastX = 0;
var lastY = 0;
var overlayContainer = that.clone.wtTable.holder.parentNode;
$(document.body).on('mousemove.' + this.instance.guid, function (event) {
if (!that.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
if ((event.clientX - lastX > -5 && event.clientX - lastX < 5) && (event.clientY - lastY > -5 && event.clientY - lastY < 5)) {
return; //ignore minor mouse movement
}
lastX = event.clientX;
lastY = event.clientY;
WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugHidden');
WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugVisible');
clearTimeout(lastTimeout);
lastTimeout = setTimeout(function () {
WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugHidden');
WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugVisible');
}, 1000);
});
}
WalkontableDebugOverlay.prototype = new WalkontableOverlay();
WalkontableDebugOverlay.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box = this.instance.wtTable.holder.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
};
WalkontableDebugOverlay.prototype.prepare = function () {
};
WalkontableDebugOverlay.prototype.refresh = function (selectionsOnly) {
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableDebugOverlay.prototype.getScrollPosition = function () {
};
WalkontableDebugOverlay.prototype.getLastCell = function () {
};
WalkontableDebugOverlay.prototype.applyToDOM = function () {
};
WalkontableDebugOverlay.prototype.scrollTo = function () {
};
WalkontableDebugOverlay.prototype.readWindowSize = function () {
};
WalkontableDebugOverlay.prototype.readSettings = function () {
};
function WalkontableDom() {
}
//goes up the DOM tree (including given element) until it finds an element that matches the nodeName
WalkontableDom.prototype.closest = function (elem, nodeNames, until) {
while (elem != null && elem !== until) {
if (elem.nodeType === 1 && nodeNames.indexOf(elem.nodeName) > -1) {
return elem;
}
elem = elem.parentNode;
}
return null;
};
//goes up the DOM tree and checks if element is child of another element
WalkontableDom.prototype.isChildOf = function (child, parent) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
/**
* Counts index of element within its parent
* WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable
* Otherwise would need to check for nodeType or use previousElementSibling
* @see http://jsperf.com/sibling-index/10
* @param {Element} elem
* @return {Number}
*/
WalkontableDom.prototype.index = function (elem) {
var i = 0;
while (elem = elem.previousSibling) {
++i
}
return i;
};
if (document.documentElement.classList) {
// HTML5 classList API
WalkontableDom.prototype.hasClass = function (ele, cls) {
return ele.classList.contains(cls);
};
WalkontableDom.prototype.addClass = function (ele, cls) {
ele.classList.add(cls);
};
WalkontableDom.prototype.removeClass = function (ele, cls) {
ele.classList.remove(cls);
};
}
else {
//http://snipplr.com/view/3561/addclass-removeclass-hasclass/
WalkontableDom.prototype.hasClass = function (ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
WalkontableDom.prototype.addClass = function (ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
};
WalkontableDom.prototype.removeClass = function (ele, cls) {
if (this.hasClass(ele, cls)) { //is this really needed?
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ').trim(); //String.prototype.trim is defined in polyfill.js
}
};
}
/*//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
WalkontableDom.prototype.addEvent = (function () {
var that = this;
if (document.addEventListener) {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.addEventListener(type, cb, false);
}
else if (elem && elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
that.addEvent(elem[i], type, cb);
}
}
};
}
else {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.attachEvent('on' + type, function () {
//normalize
//http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
var e = window['event'];
e.target = e.srcElement;
//e.offsetX = e.layerX;
//e.offsetY = e.layerY;
e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement;
if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug
return cb.call(elem, e)
});
}
else if (elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
that.addEvent(elem[i], type, cb);
}
}
};
}
})();
WalkontableDom.prototype.triggerEvent = function (element, eventName, target) {
var event;
if (document.createEvent) {
event = document.createEvent("MouseEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.target = target;
if (document.createEvent) {
target.dispatchEvent(event);
} else {
target.fireEvent("on" + event.eventType, event);
}
};*/
WalkontableDom.prototype.removeTextNodes = function (elem, parent) {
if (elem.nodeType === 3) {
parent.removeChild(elem); //bye text nodes!
}
else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) {
var childs = elem.childNodes;
for (var i = childs.length - 1; i >= 0; i--) {
this.removeTextNodes(childs[i], elem);
}
}
};
/**
* Remove childs function
* WARNING - this doesn't unload events and data attached by jQuery
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method
* @param element
* @returns {void}
*/
//
WalkontableDom.prototype.empty = function (element) {
var child;
while (child = element.lastChild) {
element.removeChild(child);
}
};
WalkontableDom.prototype.HTML_CHARACTERS = /(<(.*)>|&(.*);)/;
/**
* Insert content into element trying avoid innerHTML method.
* @return {void}
*/
WalkontableDom.prototype.fastInnerHTML = function (element, content) {
if (this.HTML_CHARACTERS.test(content)) {
element.innerHTML = content;
}
else {
this.fastInnerText(element, content);
}
};
/**
* Insert text content into element
* @return {void}
*/
if (document.createTextNode('test').textContent) { //STANDARDS
WalkontableDom.prototype.fastInnerText = function (element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
//fast lane - replace existing text node
//http://jsperf.com/replace-text-vs-reuse
child.textContent = content;
}
else {
//slow lane - empty element and insert a text node
this.empty(element);
element.appendChild(document.createTextNode(content));
}
};
}
else { //IE8
WalkontableDom.prototype.fastInnerText = function (element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
//fast lane - replace existing text node
//http://jsperf.com/replace-text-vs-reuse
child.data = content;
}
else {
//slow lane - empty element and insert a text node
this.empty(element);
element.appendChild(document.createTextNode(content));
}
};
}
/**
* Returns true/false depending if element has offset parent
* @param elem
* @returns {boolean}
*/
/*if (document.createTextNode('test').textContent) { //STANDARDS
WalkontableDom.prototype.hasOffsetParent = function (elem) {
return !!elem.offsetParent;
}
}
else {
WalkontableDom.prototype.hasOffsetParent = function (elem) {
try {
if (!elem.offsetParent) {
return false;
}
}
catch (e) {
return false; //IE8 throws "Unspecified error" when offsetParent is not found - we catch it here
}
return true;
}
}*/
/**
* Returns true if element is attached to the DOM and visible, false otherwise
* @param elem
* @returns {boolean}
*/
WalkontableDom.prototype.isVisible = function (elem) {
//fast method according to benchmarks, but requires layout so slow in our case
/*
if (!WalkontableDom.prototype.hasOffsetParent(elem)) {
return false; //fixes problem with UI Bootstrap <tabs> directive
}
// if (elem.offsetWidth > 0 || (elem.parentNode && elem.parentNode.offsetWidth > 0)) { //IE10 was mistaken here
if (elem.offsetWidth > 0) {
return true;
}
*/
//slow method
var next = elem;
while (next !== document.documentElement) { //until <html> reached
if (next === null) { //parent detached from DOM
return false;
}
else if (next.nodeType === 11) { //nodeType == 1 -> DOCUMENT_FRAGMENT_NODE
if (next.host) { //this is Web Components Shadow DOM
//see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation
//according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet
if (next.host.impl) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled
return WalkontableDom.prototype.isVisible(next.host.impl);
}
else if (next.host) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled
return WalkontableDom.prototype.isVisible(next.host);
}
else {
throw new Error("Lost in Web Components world");
}
}
else {
return false; //this is a node detached from document in IE8
}
}
else if (next.style.display === 'none') {
return false;
}
next = next.parentNode;
}
return true;
};
/**
* Returns elements top and left offset relative to the document. In our usage case compatible with jQuery but 2x faster
* @param {HTMLElement} elem
* @return {Object}
*/
WalkontableDom.prototype.offset = function (elem) {
if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
//fixes problem with Firefox ignoring <caption> in TABLE offset (see also WalkontableDom.prototype.outerHeight)
//http://jsperf.com/offset-vs-getboundingclientrect/8
var box = elem.getBoundingClientRect();
return {
top: box.top + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0),
left: box.left + (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0)
};
}
var offsetLeft = elem.offsetLeft
, offsetTop = elem.offsetTop
, lastElem = elem;
while (elem = elem.offsetParent) {
if (elem === document.body) { //from my observation, document.body always has scrollLeft/scrollTop == 0
break;
}
offsetLeft += elem.offsetLeft;
offsetTop += elem.offsetTop;
lastElem = elem;
}
if (lastElem && lastElem.style.position === 'fixed') { //slow - http://jsperf.com/offset-vs-getboundingclientrect/6
//if(lastElem !== document.body) { //faster but does gives false positive in Firefox
offsetLeft += window.pageXOffset || document.documentElement.scrollLeft;
offsetTop += window.pageYOffset || document.documentElement.scrollTop;
}
return {
left: offsetLeft,
top: offsetTop
};
};
WalkontableDom.prototype.getComputedStyle = function (elem) {
return elem.currentStyle || document.defaultView.getComputedStyle(elem);
};
WalkontableDom.prototype.outerWidth = function (elem) {
return elem.offsetWidth;
};
WalkontableDom.prototype.outerHeight = function (elem) {
if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
//fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight
//jQuery (1.10.1) still has this unsolved
//may be better to just switch to getBoundingClientRect
//http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/
//http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html
//http://bugs.jquery.com/ticket/2196
//http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140
return elem.offsetHeight + elem.firstChild.offsetHeight;
}
else {
return elem.offsetHeight;
}
};
(function () {
var hasCaptionProblem;
function detectCaptionProblem() {
var TABLE = document.createElement('TABLE');
TABLE.style.borderSpacing = 0;
TABLE.style.borderWidth = 0;
TABLE.style.padding = 0;
var TBODY = document.createElement('TBODY');
TABLE.appendChild(TBODY);
TBODY.appendChild(document.createElement('TR'));
TBODY.firstChild.appendChild(document.createElement('TD'));
TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>';
var CAPTION = document.createElement('CAPTION');
CAPTION.innerHTML = 'c<br>c<br>c<br>c';
CAPTION.style.padding = 0;
CAPTION.style.margin = 0;
TABLE.insertBefore(CAPTION, TBODY);
document.body.appendChild(TABLE);
hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); //boolean
document.body.removeChild(TABLE);
}
WalkontableDom.prototype.hasCaptionProblem = function () {
if (hasCaptionProblem === void 0) {
detectCaptionProblem();
}
return hasCaptionProblem;
};
/**
* Returns caret position in text input
* @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea
* @return {Number}
*/
WalkontableDom.prototype.getCaretPosition = function (el) {
if (el.selectionStart) {
return el.selectionStart;
}
else if (document.selection) { //IE8
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
/**
* Sets caret position in text input
* @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
* @param {Element} el
* @param {Number} pos
* @param {Number} endPos
*/
WalkontableDom.prototype.setCaretPosition = function (el, pos, endPos) {
if (endPos === void 0) {
endPos = pos;
}
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(pos, endPos);
}
else if (el.createTextRange) { //IE8
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', endPos);
range.moveStart('character', pos);
range.select();
}
};
var cachedScrollbarWidth;
//http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes
function walkontableCalculateScrollbarWidth() {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
(document.body || document.documentElement).appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
(document.body || document.documentElement).removeChild(outer);
return (w1 - w2);
}
/**
* Returns the computed width of the native browser scroll bar
* @return {Number} width
*/
WalkontableDom.prototype.getScrollbarWidth = function () {
if (cachedScrollbarWidth === void 0) {
cachedScrollbarWidth = walkontableCalculateScrollbarWidth();
}
return cachedScrollbarWidth;
}
})();
function WalkontableEvent(instance) {
var that = this;
//reference to instance
this.instance = instance;
this.wtDom = this.instance.wtDom;
var dblClickOrigin = [null, null];
var dblClickTimeout = [null, null];
var onMouseDown = function (event) {
var cell = that.parentCell(event.target);
if (that.wtDom.hasClass(event.target, 'corner')) {
that.instance.getSetting('onCellCornerMouseDown', event, event.target);
}
else if (cell.TD && cell.TD.nodeName === 'TD') {
if (that.instance.hasSetting('onCellMouseDown')) {
that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD);
}
}
if (event.button !== 2) { //if not right mouse button
if (cell.TD && cell.TD.nodeName === 'TD') {
dblClickOrigin[0] = cell.TD;
clearTimeout(dblClickTimeout[0]);
dblClickTimeout[0] = setTimeout(function () {
dblClickOrigin[0] = null;
}, 1000);
}
}
};
var lastMouseOver;
var onMouseOver = function (event) {
if (that.instance.hasSetting('onCellMouseOver')) {
var TABLE = that.instance.wtTable.TABLE;
var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE);
if (TD && TD !== lastMouseOver && that.wtDom.isChildOf(TD, TABLE)) {
lastMouseOver = TD;
if (TD.nodeName === 'TD') {
that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(TD), TD);
}
}
}
};
/* var lastMouseOut;
var onMouseOut = function (event) {
if (that.instance.hasSetting('onCellMouseOut')) {
var TABLE = that.instance.wtTable.TABLE;
var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE);
if (TD && TD !== lastMouseOut && that.wtDom.isChildOf(TD, TABLE)) {
lastMouseOut = TD;
if (TD.nodeName === 'TD') {
that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(TD), TD);
}
}
}
};*/
var onMouseUp = function (event) {
if (event.button !== 2) { //if not right mouse button
var cell = that.parentCell(event.target);
if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) {
if (that.wtDom.hasClass(event.target, 'corner')) {
that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD);
}
else if (cell.TD) {
that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD);
}
dblClickOrigin[0] = null;
dblClickOrigin[1] = null;
}
else if (cell.TD === dblClickOrigin[0]) {
dblClickOrigin[1] = cell.TD;
clearTimeout(dblClickTimeout[1]);
dblClickTimeout[1] = setTimeout(function () {
dblClickOrigin[1] = null;
}, 500);
}
}
};
$(this.instance.wtTable.holder).on('mousedown', onMouseDown);
$(this.instance.wtTable.TABLE).on('mouseover', onMouseOver);
// $(this.instance.wtTable.TABLE).on('mouseout', onMouseOut);
$(this.instance.wtTable.holder).on('mouseup', onMouseUp);
}
WalkontableEvent.prototype.parentCell = function (elem) {
var cell = {};
var TABLE = this.instance.wtTable.TABLE;
var TD = this.wtDom.closest(elem, ['TD', 'TH'], TABLE);
if (TD && this.wtDom.isChildOf(TD, TABLE)) {
cell.coords = this.instance.wtTable.getCoords(TD);
cell.TD = TD;
}
else if (this.wtDom.hasClass(elem, 'wtBorder') && this.wtDom.hasClass(elem, 'current')) {
cell.coords = this.instance.selections.current.selected[0];
cell.TD = this.instance.wtTable.getCell(cell.coords);
}
return cell;
};
WalkontableEvent.prototype.destroy = function () {
clearTimeout(this.dblClickTimeout0);
clearTimeout(this.dblClickTimeout1);
};
function walkontableRangesIntersect() {
var from = arguments[0];
var to = arguments[1];
for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) {
if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) {
return true;
}
}
return false;
}
/**
* Generates a random hex string. Used as namespace for Walkontable instance events.
* @return {String} - 16 character random string: "92b1bfc74ec4"
*/
function walkontableRandomString() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + s4() + s4();
}
/**
* http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html
*/
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (/* function */ callback, /* DOMElement */ element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = (function () {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
})();
//http://snipplr.com/view/13523/
//modified for speed
//http://jsperf.com/getcomputedstyle-vs-style-vs-css/8
if (!window.getComputedStyle) {
(function () {
var elem;
var styleObj = {
getPropertyValue: function getPropertyValue(prop) {
if (prop == 'float') prop = 'styleFloat';
return elem.currentStyle[prop.toUpperCase()] || null;
}
};
window.getComputedStyle = function (el) {
elem = el;
return styleObj;
}
})();
}
/**
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
*/
if (!String.prototype.trim) {
var trimRegex = /^\s+|\s+$/g;
String.prototype.trim = function () {
return this.replace(trimRegex, '');
};
}
/**
* WalkontableRowFilter
* @constructor
*/
function WalkontableRowFilter() {
}
WalkontableRowFilter.prototype = new WalkontableCellFilter();
WalkontableRowFilter.prototype.readSettings = function (instance) {
if (instance.cloneOverlay instanceof WalkontableDebugOverlay) {
this.offset = 0;
}
else {
this.offset = instance.wtSettings.settings.offsetRow;
}
this.total = instance.getSetting('totalRows');
this.fixedCount = instance.getSetting('fixedRowsTop');
};
/**
* WalkontableRowStrategy
* @param containerSizeFn
* @param sizeAtIndex
* @constructor
*/
function WalkontableRowStrategy(instance, containerSizeFn, sizeAtIndex) {
WalkontableCellStrategy.apply(this, arguments);
this.containerSizeFn = containerSizeFn;
this.sizeAtIndex = sizeAtIndex;
this.cellSizesSum = 0;
this.cellSizes = [];
this.cellCount = 0;
this.remainingSize = -Infinity;
}
WalkontableRowStrategy.prototype = new WalkontableCellStrategy();
WalkontableRowStrategy.prototype.add = function (i, TD, reverse) {
if (!this.isLastIncomplete() && this.remainingSize != 0) {
var size = this.sizeAtIndex(i, TD);
if (size === void 0) {
return false; //total rows exceeded
}
var containerSize = this.getContainerSize(this.cellSizesSum + size);
if (reverse) {
this.cellSizes.unshift(size);
}
else {
this.cellSizes.push(size);
}
this.cellSizesSum += size;
this.cellCount++;
this.remainingSize = this.cellSizesSum - containerSize;
if (reverse && this.isLastIncomplete()) { //something is outside of the screen, maybe even some full rows?
return false;
}
return true;
}
return false;
};
WalkontableRowStrategy.prototype.remove = function () {
var size = this.cellSizes.pop();
this.cellSizesSum -= size;
this.cellCount--;
this.remainingSize -= size;
};
WalkontableRowStrategy.prototype.removeOutstanding = function () {
while (this.cellCount > 0 && this.cellSizes[this.cellCount - 1] < this.remainingSize) { //this row is completely off screen!
this.remove();
}
};
function WalkontableScroll(instance) {
this.instance = instance;
}
WalkontableScroll.prototype.scrollVertical = function (delta) {
if (!this.instance.drawn) {
throw new Error('scrollVertical can only be called after table was drawn to DOM');
}
var instance = this.instance
, newOffset
, offset = instance.getSetting('offsetRow')
, fixedCount = instance.getSetting('fixedRowsTop')
, total = instance.getSetting('totalRows')
, maxSize = instance.wtViewport.getViewportHeight();
if (total > 0) {
newOffset = this.scrollLogicVertical(delta, offset, total, fixedCount, maxSize, function (row) {
if (row - offset < fixedCount && row - offset >= 0) {
return instance.getSetting('rowHeight', row - offset);
}
else {
return instance.getSetting('rowHeight', row);
}
}, function (isReverse) {
instance.wtTable.verticalRenderReverse = isReverse;
});
}
else {
newOffset = 0;
}
if (newOffset !== offset) {
this.instance.wtScrollbars.vertical.scrollTo(newOffset);
}
return instance;
};
WalkontableScroll.prototype.scrollHorizontal = function (delta) {
if (!this.instance.drawn) {
throw new Error('scrollHorizontal can only be called after table was drawn to DOM');
}
var instance = this.instance
, newOffset
, offset = instance.getSetting('offsetColumn')
, fixedCount = instance.getSetting('fixedColumnsLeft')
, total = instance.getSetting('totalColumns')
, maxSize = instance.wtViewport.getViewportWidth();
if (total > 0) {
newOffset = this.scrollLogicHorizontal(delta, offset, total, fixedCount, maxSize, function (col) {
if (col - offset < fixedCount && col - offset >= 0) {
return instance.getSetting('columnWidth', col - offset);
}
else {
return instance.getSetting('columnWidth', col);
}
});
}
else {
newOffset = 0;
}
if (newOffset !== offset) {
this.instance.wtScrollbars.horizontal.scrollTo(newOffset);
}
return instance;
};
WalkontableScroll.prototype.scrollLogicVertical = function (delta, offset, total, fixedCount, maxSize, cellSizeFn, setReverseRenderFn) {
var newOffset = offset + delta;
if (newOffset >= total - fixedCount) {
newOffset = total - fixedCount - 1;
setReverseRenderFn(true);
}
if (newOffset < 0) {
newOffset = 0;
}
return newOffset;
};
WalkontableScroll.prototype.scrollLogicHorizontal = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) {
var newOffset = offset + delta
, sum = 0
, col;
if (newOffset > fixedCount) {
if (newOffset >= total - fixedCount) {
newOffset = total - fixedCount - 1;
}
col = newOffset;
while (sum < maxSize && col < total) {
sum += cellSizeFn(col);
col++;
}
if (sum < maxSize) {
while (newOffset > 0) {
//if sum still less than available width, we cannot scroll that far (must move offset to the left)
sum += cellSizeFn(newOffset - 1);
if (sum < maxSize) {
newOffset--;
}
else {
break;
}
}
}
}
else if (newOffset < 0) {
newOffset = 0;
}
return newOffset;
};
/**
* Scrolls viewport to a cell by minimum number of cells
*/
WalkontableScroll.prototype.scrollViewport = function (coords) {
if (!this.instance.drawn) {
return;
}
var offsetRow = this.instance.getSetting('offsetRow')
, offsetColumn = this.instance.getSetting('offsetColumn')
, lastVisibleRow = this.instance.wtTable.getLastVisibleRow()
, totalRows = this.instance.getSetting('totalRows')
, totalColumns = this.instance.getSetting('totalColumns')
, fixedRowsTop = this.instance.getSetting('fixedRowsTop')
, fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft');
if (this.instance.getSetting('nativeScrollbars')) {
var TD = this.instance.wtTable.getCell(coords);
if (typeof TD === 'object') {
var offset = WalkontableDom.prototype.offset(TD);
var outerWidth = WalkontableDom.prototype.outerWidth(TD);
var outerHeight = WalkontableDom.prototype.outerHeight(TD);
var scrollX = this.instance.wtScrollbars.horizontal.getScrollPosition();
var scrollY = this.instance.wtScrollbars.vertical.getScrollPosition();
var clientWidth = WalkontableDom.prototype.outerWidth(this.instance.wtScrollbars.horizontal.scrollHandler);
var clientHeight = WalkontableDom.prototype.outerHeight(this.instance.wtScrollbars.vertical.scrollHandler);
if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
offset.left = offset.left - WalkontableDom.prototype.offset(this.instance.wtScrollbars.horizontal.scrollHandler).left;
}
if (this.instance.wtScrollbars.vertical.scrollHandler !== window) {
offset.top = offset.top - WalkontableDom.prototype.offset(this.instance.wtScrollbars.vertical.scrollHandler).top;
}
clientWidth -= 20;
clientHeight -= 20;
if (outerWidth < clientWidth) {
if (offset.left < scrollX) {
this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left);
}
else if (offset.left + outerWidth > scrollX + clientWidth) {
this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left - clientWidth + outerWidth);
}
}
if (outerHeight < clientHeight) {
if (offset.top < scrollY) {
this.instance.wtScrollbars.vertical.setScrollPosition(offset.top);
}
else if (offset.top + outerHeight > scrollY + clientHeight) {
this.instance.wtScrollbars.vertical.setScrollPosition(offset.top - clientHeight + outerHeight);
}
}
return;
}
}
if (coords[0] < 0 || coords[0] > totalRows - 1) {
throw new Error('row ' + coords[0] + ' does not exist');
}
else if (coords[1] < 0 || coords[1] > totalColumns - 1) {
throw new Error('column ' + coords[1] + ' does not exist');
}
if (coords[0] > lastVisibleRow) {
// this.scrollVertical(coords[0] - lastVisibleRow + 1);
this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
this.instance.wtTable.verticalRenderReverse = true;
}
else if (coords[0] === lastVisibleRow && this.instance.wtTable.rowStrategy.isLastIncomplete()) {
// this.scrollVertical(coords[0] - lastVisibleRow + 1);
this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
this.instance.wtTable.verticalRenderReverse = true;
}
else if (coords[0] - fixedRowsTop < offsetRow) {
this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
}
else {
this.scrollVertical(0); //Craig's issue: remove row from the last scroll page should scroll viewport a row up if needed
}
if (this.instance.wtTable.isColumnBeforeViewport(coords[1])) {
//scroll left
this.instance.wtScrollbars.horizontal.scrollTo(coords[1] - fixedColumnsLeft);
}
else if (this.instance.wtTable.isColumnAfterViewport(coords[1]) || (this.instance.wtTable.getLastVisibleColumn() === coords[1] && !this.instance.wtTable.isLastColumnFullyVisible())) {
//scroll right
var sum = 0;
for (var i = 0; i < fixedColumnsLeft; i++) {
sum += this.instance.getSetting('columnWidth', i);
}
var scrollTo = coords[1];
sum += this.instance.getSetting('columnWidth', scrollTo);
var available = this.instance.wtViewport.getViewportWidth();
if (sum < available) {
var next = this.instance.getSetting('columnWidth', scrollTo - 1);
while (sum + next <= available && scrollTo >= fixedColumnsLeft) {
scrollTo--;
sum += next;
next = this.instance.getSetting('columnWidth', scrollTo - 1);
}
}
this.instance.wtScrollbars.horizontal.scrollTo(scrollTo - fixedColumnsLeft);
}
/*else {
//no scroll
}*/
return this.instance;
};
function WalkontableScrollbar() {
}
WalkontableScrollbar.prototype.init = function () {
var that = this;
//reference to instance
this.$table = $(this.instance.wtTable.TABLE);
//create elements
this.slider = document.createElement('DIV');
this.sliderStyle = this.slider.style;
this.sliderStyle.position = 'absolute';
this.sliderStyle.top = '0';
this.sliderStyle.left = '0';
this.sliderStyle.display = 'none';
this.slider.className = 'dragdealer ' + this.type;
this.handle = document.createElement('DIV');
this.handleStyle = this.handle.style;
this.handle.className = 'handle';
this.slider.appendChild(this.handle);
this.container = this.instance.wtTable.holder;
this.container.appendChild(this.slider);
var firstRun = true;
this.dragTimeout = null;
var dragDelta;
var dragRender = function () {
that.onScroll(dragDelta);
};
this.dragdealer = new Dragdealer(this.slider, {
vertical: (this.type === 'vertical'),
horizontal: (this.type === 'horizontal'),
slide: false,
speed: 100,
animationCallback: function (x, y) {
if (firstRun) {
firstRun = false;
return;
}
that.skipRefresh = true;
dragDelta = that.type === 'vertical' ? y : x;
if (that.dragTimeout === null) {
that.dragTimeout = setInterval(dragRender, 100);
dragRender();
}
},
callback: function (x, y) {
that.skipRefresh = false;
clearInterval(that.dragTimeout);
that.dragTimeout = null;
dragDelta = that.type === 'vertical' ? y : x;
that.onScroll(dragDelta);
}
});
this.skipRefresh = false;
};
WalkontableScrollbar.prototype.onScroll = function (delta) {
if (this.instance.drawn) {
this.readSettings();
if (this.total > this.visibleCount) {
var newOffset = Math.round(this.handlePosition * this.total / this.sliderSize);
if (delta === 1) {
if (this.type === 'vertical') {
this.instance.scrollVertical(Infinity).draw();
}
else {
this.instance.scrollHorizontal(Infinity).draw();
}
}
else if (newOffset !== this.offset) { //is new offset different than old offset
if (this.type === 'vertical') {
this.instance.scrollVertical(newOffset - this.offset).draw();
}
else {
this.instance.scrollHorizontal(newOffset - this.offset).draw();
}
}
else {
this.refresh();
}
}
}
};
/**
* Returns what part of the scroller should the handle take
* @param viewportCount {Number} number of visible rows or columns
* @param totalCount {Number} total number of rows or columns
* @return {Number} 0..1
*/
WalkontableScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) {
if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) {
return 1;
}
return 1 / totalCount;
};
WalkontableScrollbar.prototype.prepare = function () {
if (this.skipRefresh) {
return;
}
var ratio = this.getHandleSizeRatio(this.visibleCount, this.total);
if (((ratio === 1 || isNaN(ratio)) && this.scrollMode === 'auto') || this.scrollMode === 'none') {
//isNaN is needed because ratio equals NaN when totalRows/totalColumns equals 0
this.visible = false;
}
else {
this.visible = true;
}
};
WalkontableScrollbar.prototype.refresh = function () {
if (this.skipRefresh) {
return;
}
else if (!this.visible) {
this.sliderStyle.display = 'none';
return;
}
var ratio
, sliderSize
, handleSize
, handlePosition
, visibleCount = this.visibleCount
, tableWidth = this.instance.wtViewport.getWorkspaceWidth()
, tableHeight = this.instance.wtViewport.getWorkspaceHeight();
if (tableWidth === Infinity) {
tableWidth = this.instance.wtViewport.getWorkspaceActualWidth();
}
if (tableHeight === Infinity) {
tableHeight = this.instance.wtViewport.getWorkspaceActualHeight();
}
if (this.type === 'vertical') {
if (this.instance.wtTable.rowStrategy.isLastIncomplete()) {
visibleCount--;
}
sliderSize = tableHeight - 2; //2 is sliders border-width
this.sliderStyle.top = this.instance.wtDom.offset(this.$table[0]).top - this.instance.wtDom.offset(this.container).top + 'px';
this.sliderStyle.left = tableWidth - 1 + 'px'; //1 is sliders border-width
this.sliderStyle.height = Math.max(sliderSize, 0) + 'px';
}
else { //horizontal
sliderSize = tableWidth - 2; //2 is sliders border-width
this.sliderStyle.left = this.instance.wtDom.offset(this.$table[0]).left - this.instance.wtDom.offset(this.container).left + 'px';
this.sliderStyle.top = tableHeight - 1 + 'px'; //1 is sliders border-width
this.sliderStyle.width = Math.max(sliderSize, 0) + 'px';
}
ratio = this.getHandleSizeRatio(visibleCount, this.total);
handleSize = Math.round(sliderSize * ratio);
if (handleSize < 10) {
handleSize = 15;
}
handlePosition = Math.floor(sliderSize * (this.offset / this.total));
if (handleSize + handlePosition > sliderSize) {
handlePosition = sliderSize - handleSize;
}
if (this.type === 'vertical') {
this.handleStyle.height = handleSize + 'px';
this.handleStyle.top = handlePosition + 'px';
}
else { //horizontal
this.handleStyle.width = handleSize + 'px';
this.handleStyle.left = handlePosition + 'px';
}
this.sliderStyle.display = 'block';
};
WalkontableScrollbar.prototype.destroy = function () {
clearInterval(this.dragdealer.interval);
};
///
var WalkontableVerticalScrollbar = function (instance) {
this.instance = instance;
this.type = 'vertical';
this.init();
};
WalkontableVerticalScrollbar.prototype = new WalkontableScrollbar();
WalkontableVerticalScrollbar.prototype.scrollTo = function (cell) {
this.instance.update('offsetRow', cell);
};
WalkontableVerticalScrollbar.prototype.readSettings = function () {
this.scrollMode = this.instance.getSetting('scrollV');
this.offset = this.instance.getSetting('offsetRow');
this.total = this.instance.getSetting('totalRows');
this.visibleCount = this.instance.wtTable.rowStrategy.countVisible();
if(this.visibleCount > 1 && this.instance.wtTable.rowStrategy.isLastIncomplete()) {
this.visibleCount--;
}
this.handlePosition = parseInt(this.handleStyle.top, 10);
this.sliderSize = parseInt(this.sliderStyle.height, 10);
this.fixedCount = this.instance.getSetting('fixedRowsTop');
};
///
var WalkontableHorizontalScrollbar = function (instance) {
this.instance = instance;
this.type = 'horizontal';
this.init();
};
WalkontableHorizontalScrollbar.prototype = new WalkontableScrollbar();
WalkontableHorizontalScrollbar.prototype.scrollTo = function (cell) {
this.instance.update('offsetColumn', cell);
};
WalkontableHorizontalScrollbar.prototype.readSettings = function () {
this.scrollMode = this.instance.getSetting('scrollH');
this.offset = this.instance.getSetting('offsetColumn');
this.total = this.instance.getSetting('totalColumns');
this.visibleCount = this.instance.wtTable.columnStrategy.countVisible();
if(this.visibleCount > 1 && this.instance.wtTable.columnStrategy.isLastIncomplete()) {
this.visibleCount--;
}
this.handlePosition = parseInt(this.handleStyle.left, 10);
this.sliderSize = parseInt(this.sliderStyle.width, 10);
this.fixedCount = this.instance.getSetting('fixedColumnsLeft');
};
WalkontableHorizontalScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) {
if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) {
return 1;
}
return viewportCount / totalCount;
};
function WalkontableCornerScrollbarNative(instance) {
this.instance = instance;
this.init();
this.clone = this.makeClone('corner');
}
WalkontableCornerScrollbarNative.prototype = new WalkontableOverlay();
WalkontableCornerScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var top = Math.ceil(box.top, 10);
var bottom = Math.ceil(box.bottom, 10);
if (top < 0 && bottom > 0) {
elem.style.top = '0';
}
else {
elem.style.top = top + 'px';
}
var left = Math.ceil(box.left, 10);
var right = Math.ceil(box.right, 10);
if (left < 0 && right > 0) {
elem.style.left = '0';
}
else {
elem.style.left = left + 'px';
}
}
else {
box = this.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
elem.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px';
elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};
WalkontableCornerScrollbarNative.prototype.prepare = function () {
};
WalkontableCornerScrollbarNative.prototype.refresh = function (selectionsOnly) {
this.measureBefore = 0;
this.measureAfter = 0;
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableCornerScrollbarNative.prototype.getScrollPosition = function () {
};
WalkontableCornerScrollbarNative.prototype.getLastCell = function () {
};
WalkontableCornerScrollbarNative.prototype.applyToDOM = function () {
};
WalkontableCornerScrollbarNative.prototype.scrollTo = function () {
};
WalkontableCornerScrollbarNative.prototype.readWindowSize = function () {
};
WalkontableCornerScrollbarNative.prototype.readSettings = function () {
};
function WalkontableHorizontalScrollbarNative(instance) {
this.instance = instance;
this.type = 'horizontal';
this.cellSize = 50;
this.init();
this.clone = this.makeClone('left');
}
WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay();
//resetFixedPosition (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var left = Math.ceil(box.left, 10);
var right = Math.ceil(box.right, 10);
if (left < 0 && right > 0) {
elem.style.left = '0';
}
else {
elem.style.left = left + 'px';
}
}
else {
box = this.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
};
//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.react = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var overlayContainer = this.clone.wtTable.holder.parentNode;
if (this.instance.wtScrollbars.vertical.scrollHandler === window) {
var box = this.instance.wtTable.hider.getBoundingClientRect();
overlayContainer.style.top = Math.ceil(box.top, 10) + 'px';
overlayContainer.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 'px';
}
else {
this.clone.wtTable.holder.style.top = -(this.instance.wtScrollbars.vertical.windowScrollPosition - this.instance.wtScrollbars.vertical.measureBefore) + 'px';
overlayContainer.style.height = this.instance.wtViewport.getWorkspaceHeight() + 'px'
}
overlayContainer.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; //4 is for the box shadow
};
WalkontableHorizontalScrollbarNative.prototype.prepare = function () {
};
WalkontableHorizontalScrollbarNative.prototype.refresh = function (selectionsOnly) {
this.measureBefore = 0;
this.measureAfter = 0;
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function () {
if (this.scrollHandler === window) {
return this.scrollHandler.scrollX;
}
else {
return this.scrollHandler.scrollLeft;
}
};
WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function (pos) {
this.scrollHandler.scrollLeft = pos;
};
WalkontableHorizontalScrollbarNative.prototype.onScroll = function () {
WalkontableOverlay.prototype.onScroll.apply(this, arguments);
this.instance.getSetting('onScrollHorizontally');
};
WalkontableHorizontalScrollbarNative.prototype.getLastCell = function () {
return this.instance.wtTable.getLastVisibleColumn();
};
//applyToDOM (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () {
this.fixedContainer.style.paddingLeft = this.measureBefore + 'px';
this.fixedContainer.style.paddingRight = this.measureAfter + 'px';
};
WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (cell) {
this.$scrollHandler.scrollLeft(this.tableParentOffset + cell * this.cellSize);
};
//readWindowSize (in future merge it with this.prepare?)
WalkontableHorizontalScrollbarNative.prototype.readWindowSize = function () {
if (this.scrollHandler === window) {
this.windowSize = document.documentElement.clientWidth;
this.tableParentOffset = this.instance.wtTable.holderOffset.left;
}
else {
this.windowSize = WalkontableDom.prototype.outerWidth(this.scrollHandler);
this.tableParentOffset = 0;
}
this.windowScrollPosition = this.getScrollPosition();
};
//readSettings (in future merge it with this.prepare?)
WalkontableHorizontalScrollbarNative.prototype.readSettings = function () {
this.offset = this.instance.getSetting('offsetColumn');
this.total = this.instance.getSetting('totalColumns');
};
function WalkontableVerticalScrollbarNative(instance) {
this.instance = instance;
this.type = 'vertical';
this.cellSize = 23;
this.init();
this.clone = this.makeClone('top');
}
WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay();
//resetFixedPosition (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var top = Math.ceil(box.top, 10);
var bottom = Math.ceil(box.bottom, 10);
if (top < 0 && bottom > 0) {
elem.style.top = '0';
}
else {
elem.style.top = top + 'px';
}
}
else {
box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
if (this.instance.wtScrollbars.horizontal.scrollHandler === window) {
elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px';
}
else {
elem.style.width = WalkontableDom.prototype.outerWidth(this.instance.wtTable.holder.parentNode) + 'px';
}
elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};
//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.react = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
var elem = this.clone.wtTable.holder.parentNode;
elem.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px';
}
};
WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () {
if (this.scrollHandler === window) {
return this.scrollHandler.scrollY;
}
else {
return this.scrollHandler.scrollTop;
}
};
WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) {
this.scrollHandler.scrollTop = pos;
};
WalkontableVerticalScrollbarNative.prototype.onScroll = function (forcePosition) {
WalkontableOverlay.prototype.onScroll.apply(this, arguments);
var scrollDelta;
var newOffset = 0;
if (1 == 1 || this.windowScrollPosition > this.tableParentOffset) {
scrollDelta = this.windowScrollPosition - this.tableParentOffset;
partialOffset = 0;
if (scrollDelta > 0) {
var sum = 0;
var last;
for (var i = 0; i < this.total; i++) {
last = this.instance.getSetting('rowHeight', i);
sum += last;
if (sum > scrollDelta) {
break;
}
}
if (this.offset > 0) {
partialOffset = (sum - scrollDelta);
}
newOffset = i;
newOffset = Math.min(newOffset, this.total);
}
}
this.curOuts = newOffset > this.maxOuts ? this.maxOuts : newOffset;
newOffset -= this.curOuts;
this.instance.update('offsetRow', newOffset);
this.readSettings(); //read new offset
this.instance.draw();
this.instance.getSetting('onScrollVertically');
};
WalkontableVerticalScrollbarNative.prototype.getLastCell = function () {
return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1;
};
var partialOffset = 0;
WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) {
var sum = 0;
while (from < length) {
sum += this.instance.getSetting('rowHeight', from);
from++;
}
return sum;
};
//applyToDOM (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () {
var headerSize = this.instance.wtViewport.getColumnHeaderHeight();
this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow
this.fixed.style.top = this.measureBefore + 'px';
this.fixed.style.bottom = '';
};
WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) {
var newY = this.tableParentOffset + cell * this.cellSize;
this.$scrollHandler.scrollTop(newY);
this.onScroll(newY);
};
//readWindowSize (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () {
if (this.scrollHandler === window) {
this.windowSize = document.documentElement.clientHeight;
this.tableParentOffset = this.instance.wtTable.holderOffset.top;
}
else {
//this.windowSize = WalkontableDom.prototype.outerHeight(this.scrollHandler);
this.windowSize = this.scrollHandler.clientHeight; //returns height without DIV scrollbar
this.tableParentOffset = 0;
}
this.windowScrollPosition = this.getScrollPosition();
};
//readSettings (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readSettings = function () {
this.offset = this.instance.getSetting('offsetRow');
this.total = this.instance.getSetting('totalRows');
};
function WalkontableScrollbars(instance) {
this.instance = instance;
if (instance.getSetting('nativeScrollbars')) {
instance.update('scrollbarWidth', instance.wtDom.getScrollbarWidth());
instance.update('scrollbarHeight', instance.wtDom.getScrollbarWidth());
this.vertical = new WalkontableVerticalScrollbarNative(instance);
this.horizontal = new WalkontableHorizontalScrollbarNative(instance);
this.corner = new WalkontableCornerScrollbarNative(instance);
if (instance.getSetting('debug')) {
this.debug = new WalkontableDebugOverlay(instance);
}
this.registerListeners();
}
else {
this.vertical = new WalkontableVerticalScrollbar(instance);
this.horizontal = new WalkontableHorizontalScrollbar(instance);
}
}
WalkontableScrollbars.prototype.registerListeners = function () {
var that = this;
var oldVerticalScrollPosition
, oldHorizontalScrollPosition
, oldBoxTop
, oldBoxLeft
, oldBoxWidth
, oldBoxHeight;
function refreshAll() {
if (!that.instance.wtTable.holder.parentNode) {
//Walkontable was detached from DOM, but this handler was not removed
that.destroy();
return;
}
that.vertical.windowScrollPosition = that.vertical.getScrollPosition();
that.horizontal.windowScrollPosition = that.horizontal.getScrollPosition();
that.box = that.instance.wtTable.hider.getBoundingClientRect();
if((that.box.width !== oldBoxWidth || that.box.height !== oldBoxHeight) && that.instance.rowHeightCache) {
//that.instance.rowHeightCache.length = 0; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table
oldBoxWidth = that.box.width;
oldBoxHeight = that.box.height;
that.instance.draw();
}
if (that.vertical.windowScrollPosition !== oldVerticalScrollPosition || that.horizontal.windowScrollPosition !== oldHorizontalScrollPosition || that.box.top !== oldBoxTop || that.box.left !== oldBoxLeft) {
that.vertical.onScroll();
that.horizontal.onScroll(); //it's done here to make sure that all onScroll's are executed before changing styles
that.vertical.react();
that.horizontal.react(); //it's done here to make sure that all onScroll's are executed before changing styles
oldVerticalScrollPosition = that.vertical.windowScrollPosition;
oldHorizontalScrollPosition = that.horizontal.windowScrollPosition;
oldBoxTop = that.box.top;
oldBoxLeft = that.box.left;
}
}
var $window = $(window);
this.vertical.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
if (this.vertical.scrollHandler !== this.horizontal.scrollHandler) {
this.horizontal.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
}
if (this.vertical.scrollHandler !== window && this.horizontal.scrollHandler !== window) {
$window.on('scroll.' + this.instance.guid, refreshAll);
}
$window.on('load.' + this.instance.guid, refreshAll);
$window.on('resize.' + this.instance.guid, refreshAll);
$(document).on('ready.' + this.instance.guid, refreshAll);
setInterval(refreshAll, 100); //Marcin - only idea I have to reposition scrollbars on CSS change of the container (container was moved using some styles after page was loaded)
};
WalkontableScrollbars.prototype.destroy = function () {
this.vertical && this.vertical.destroy();
this.horizontal && this.horizontal.destroy();
};
WalkontableScrollbars.prototype.refresh = function (selectionsOnly) {
this.horizontal && this.horizontal.readSettings();
this.vertical && this.vertical.readSettings();
this.horizontal && this.horizontal.prepare();
this.vertical && this.vertical.prepare();
this.horizontal && this.horizontal.refresh(selectionsOnly);
this.vertical && this.vertical.refresh(selectionsOnly);
this.corner && this.corner.refresh(selectionsOnly);
this.debug && this.debug.refresh(selectionsOnly);
};
function WalkontableSelection(instance, settings) {
this.instance = instance;
this.settings = settings;
this.selected = [];
if (settings.border) {
this.border = new WalkontableBorder(instance, settings);
}
}
WalkontableSelection.prototype.add = function (coords) {
this.selected.push(coords);
};
WalkontableSelection.prototype.clear = function () {
this.selected.length = 0; //http://jsperf.com/clear-arrayxxx
};
/**
* Returns the top left (TL) and bottom right (BR) selection coordinates
* @returns {Object}
*/
WalkontableSelection.prototype.getCorners = function () {
var minRow
, minColumn
, maxRow
, maxColumn
, i
, ilen = this.selected.length;
if (ilen > 0) {
minRow = maxRow = this.selected[0][0];
minColumn = maxColumn = this.selected[0][1];
if (ilen > 1) {
for (i = 1; i < ilen; i++) {
if (this.selected[i][0] < minRow) {
minRow = this.selected[i][0];
}
else if (this.selected[i][0] > maxRow) {
maxRow = this.selected[i][0];
}
if (this.selected[i][1] < minColumn) {
minColumn = this.selected[i][1];
}
else if (this.selected[i][1] > maxColumn) {
maxColumn = this.selected[i][1];
}
}
}
}
return [minRow, minColumn, maxRow, maxColumn];
};
WalkontableSelection.prototype.draw = function () {
var corners, r, c, source_r, source_c;
var visibleRows = this.instance.wtTable.rowStrategy.countVisible()
, visibleColumns = this.instance.wtTable.columnStrategy.countVisible();
if (this.selected.length) {
corners = this.getCorners();
for (r = 0; r < visibleRows; r++) {
for (c = 0; c < visibleColumns; c++) {
source_r = this.instance.wtTable.rowFilter.visibleToSource(r);
source_c = this.instance.wtTable.columnFilter.visibleToSource(c);
if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) {
//selected cell
this.instance.wtTable.currentCellCache.add(r, c, this.settings.className);
}
else if (source_r >= corners[0] && source_r <= corners[2]) {
//selection is in this row
this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName);
}
else if (source_c >= corners[1] && source_c <= corners[3]) {
//selection is in this column
this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName);
}
}
}
this.border && this.border.appear(corners); //warning! border.appear modifies corners!
}
else {
this.border && this.border.disappear();
}
};
function WalkontableSettings(instance, settings) {
var that = this;
this.instance = instance;
//default settings. void 0 means it is required, null means it can be empty
this.defaults = {
table: void 0,
debug: false, //shows WalkontableDebugOverlay
//presentation mode
scrollH: 'auto', //values: scroll (always show scrollbar), auto (show scrollbar if table does not fit in the container), none (never show scrollbar)
scrollV: 'auto', //values: see above
nativeScrollbars: false, //values: false (dragdealer), true (native)
stretchH: 'hybrid', //values: hybrid, all, last, none
currentRowClassName: null,
currentColumnClassName: null,
//data source
data: void 0,
offsetRow: 0,
offsetColumn: 0,
fixedColumnsLeft: 0,
fixedRowsTop: 0,
rowHeaders: function () {
return []
}, //this must be array of functions: [function (row, TH) {}]
columnHeaders: function () {
return []
}, //this must be array of functions: [function (column, TH) {}]
totalRows: void 0,
totalColumns: void 0,
width: null,
height: null,
cellRenderer: function (row, column, TD) {
var cellData = that.getSetting('data', row, column);
that.instance.wtDom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData);
},
columnWidth: 50,
selections: null,
hideBorderOnMouseDownOver: false,
//callbacks
onCellMouseDown: null,
onCellMouseOver: null,
// onCellMouseOut: null,
onCellDblClick: null,
onCellCornerMouseDown: null,
onCellCornerDblClick: null,
beforeDraw: null,
onDraw: null,
onScrollVertically: null,
onScrollHorizontally: null,
//constants
scrollbarWidth: 10,
scrollbarHeight: 10
};
//reference to settings
this.settings = {};
for (var i in this.defaults) {
if (this.defaults.hasOwnProperty(i)) {
if (settings[i] !== void 0) {
this.settings[i] = settings[i];
}
else if (this.defaults[i] === void 0) {
throw new Error('A required setting "' + i + '" was not provided');
}
else {
this.settings[i] = this.defaults[i];
}
}
}
}
/**
* generic methods
*/
WalkontableSettings.prototype.update = function (settings, value) {
if (value === void 0) { //settings is object
for (var i in settings) {
if (settings.hasOwnProperty(i)) {
this.settings[i] = settings[i];
}
}
}
else { //if value is defined then settings is the key
this.settings[settings] = value;
}
return this.instance;
};
WalkontableSettings.prototype.getSetting = function (key, param1, param2, param3) {
if (this[key]) {
return this[key](param1, param2, param3);
}
else {
return this._getSetting(key, param1, param2, param3);
}
};
WalkontableSettings.prototype._getSetting = function (key, param1, param2, param3) {
if (typeof this.settings[key] === 'function') {
return this.settings[key](param1, param2, param3);
}
else if (param1 !== void 0 && Object.prototype.toString.call(this.settings[key]) === '[object Array]') {
return this.settings[key][param1];
}
else {
return this.settings[key];
}
};
WalkontableSettings.prototype.has = function (key) {
return !!this.settings[key]
};
/**
* specific methods
*/
WalkontableSettings.prototype.rowHeight = function (row, TD) {
if (!this.instance.rowHeightCache) {
this.instance.rowHeightCache = []; //hack. This cache is being invalidated in WOT core.js
}
if (this.instance.rowHeightCache[row] === void 0) {
var size = 23; //guess
if (TD) {
size = this.instance.wtDom.outerHeight(TD); //measure
this.instance.rowHeightCache[row] = size; //cache only something we measured
}
return size;
}
else {
return this.instance.rowHeightCache[row];
}
};
function WalkontableTable(instance, table) {
//reference to instance
this.instance = instance;
this.TABLE = table;
this.wtDom = this.instance.wtDom;
this.wtDom.removeTextNodes(this.TABLE);
//wtSpreader
var parent = this.TABLE.parentNode;
if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
var spreader = document.createElement('DIV');
spreader.className = 'wtSpreader';
if (parent) {
parent.insertBefore(spreader, this.TABLE); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
spreader.appendChild(this.TABLE);
}
this.spreader = this.TABLE.parentNode;
//wtHider
parent = this.spreader.parentNode;
if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
var hider = document.createElement('DIV');
hider.className = 'wtHider';
if (parent) {
parent.insertBefore(hider, this.spreader); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
hider.appendChild(this.spreader);
}
this.hider = this.spreader.parentNode;
this.hiderStyle = this.hider.style;
this.hiderStyle.position = 'relative';
//wtHolder
parent = this.hider.parentNode;
if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
var holder = document.createElement('DIV');
holder.style.position = 'relative';
holder.className = 'wtHolder';
if (parent) {
parent.insertBefore(holder, this.hider); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
holder.appendChild(this.hider);
}
this.holder = this.hider.parentNode;
//bootstrap from settings
this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0];
if (!this.TBODY) {
this.TBODY = document.createElement('TBODY');
this.TABLE.appendChild(this.TBODY);
}
this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0];
if (!this.THEAD) {
this.THEAD = document.createElement('THEAD');
this.TABLE.insertBefore(this.THEAD, this.TBODY);
}
this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0];
if (!this.COLGROUP) {
this.COLGROUP = document.createElement('COLGROUP');
this.TABLE.insertBefore(this.COLGROUP, this.THEAD);
}
if (this.instance.getSetting('columnHeaders').length) {
if (!this.THEAD.childNodes.length) {
var TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
}
this.colgroupChildrenLength = this.COLGROUP.childNodes.length;
this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0;
this.tbodyChildrenLength = this.TBODY.childNodes.length;
this.oldCellCache = new WalkontableClassNameCache();
this.currentCellCache = new WalkontableClassNameCache();
this.rowFilter = new WalkontableRowFilter();
this.columnFilter = new WalkontableColumnFilter();
this.verticalRenderReverse = false;
}
WalkontableTable.prototype.refreshHiderDimensions = function () {
var height = this.instance.wtViewport.getWorkspaceHeight();
var width = this.instance.wtViewport.getWorkspaceWidth();
var spreaderStyle = this.spreader.style;
if ((height !== Infinity || width !== Infinity) && !this.instance.getSetting('nativeScrollbars')) {
if (height === Infinity) {
height = this.instance.wtViewport.getWorkspaceActualHeight();
}
if (width === Infinity) {
width = this.instance.wtViewport.getWorkspaceActualWidth();
}
this.hiderStyle.overflow = 'hidden';
spreaderStyle.position = 'absolute';
spreaderStyle.top = '0';
spreaderStyle.left = '0';
if (!this.instance.getSetting('nativeScrollbars')) {
spreaderStyle.height = '4000px';
spreaderStyle.width = '4000px';
}
if (height < 0) { //this happens with WalkontableOverlay and causes "Invalid argument" error in IE8
height = 0;
}
this.hiderStyle.height = height + 'px';
this.hiderStyle.width = width + 'px';
}
else {
spreaderStyle.position = 'relative';
spreaderStyle.width = 'auto';
spreaderStyle.height = 'auto';
}
};
WalkontableTable.prototype.refreshStretching = function () {
if (this.instance.cloneSource) {
return;
}
var instance = this.instance
, stretchH = instance.getSetting('stretchH')
, totalRows = instance.getSetting('totalRows')
, totalColumns = instance.getSetting('totalColumns')
, offsetColumn = instance.getSetting('offsetColumn');
var containerWidthFn = function (cacheWidth) {
var viewportWidth = that.instance.wtViewport.getViewportWidth(cacheWidth);
if (viewportWidth < cacheWidth && that.instance.getSetting('nativeScrollbars')) {
return Infinity; //disable stretching when viewport is bigger than sum of the cell widths
}
return viewportWidth;
};
var that = this;
var columnWidthFn = function (i) {
var source_c = that.columnFilter.visibleToSource(i);
if (source_c < totalColumns) {
return instance.getSetting('columnWidth', source_c);
}
};
if (stretchH === 'hybrid') {
if (offsetColumn > 0) {
stretchH = 'last';
}
else {
stretchH = 'none';
}
}
var containerHeightFn = function (cacheHeight) {
if (that.instance.getSetting('nativeScrollbars')) {
if (that.instance.cloneOverlay instanceof WalkontableDebugOverlay) {
return Infinity;
}
else {
return 2 * that.instance.wtViewport.getViewportHeight(cacheHeight);
}
}
return that.instance.wtViewport.getViewportHeight(cacheHeight);
};
var rowHeightFn = function (i, TD) {
if (that.instance.getSetting('nativeScrollbars')) {
return 20;
}
var source_r = that.rowFilter.visibleToSource(i);
if (source_r < totalRows) {
if (that.verticalRenderReverse && i === 0) {
return that.instance.getSetting('rowHeight', source_r, TD) - 1;
}
else {
return that.instance.getSetting('rowHeight', source_r, TD);
}
}
};
this.columnStrategy = new WalkontableColumnStrategy(instance, containerWidthFn, columnWidthFn, stretchH);
this.rowStrategy = new WalkontableRowStrategy(instance, containerHeightFn, rowHeightFn);
};
WalkontableTable.prototype.adjustAvailableNodes = function () {
var displayTds
, rowHeaders = this.instance.getSetting('rowHeaders')
, displayThs = rowHeaders.length
, columnHeaders = this.instance.getSetting('columnHeaders')
, TR
, TD
, c;
//adjust COLGROUP
while (this.colgroupChildrenLength < displayThs) {
this.COLGROUP.appendChild(document.createElement('COL'));
this.colgroupChildrenLength++;
}
this.refreshStretching(); //actually it is wrong position because it assumes rowHeader would be always 50px wide (because we measure before it is filled with text). TODO: debug
if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) {
displayTds = this.instance.getSetting('fixedColumnsLeft');
}
else {
displayTds = this.columnStrategy.cellCount;
}
//adjust COLGROUP
while (this.colgroupChildrenLength < displayTds + displayThs) {
this.COLGROUP.appendChild(document.createElement('COL'));
this.colgroupChildrenLength++;
}
while (this.colgroupChildrenLength > displayTds + displayThs) {
this.COLGROUP.removeChild(this.COLGROUP.lastChild);
this.colgroupChildrenLength--;
}
//adjust THEAD
TR = this.THEAD.firstChild;
if (columnHeaders.length) {
if (!TR) {
TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
this.theadChildrenLength = TR.childNodes.length;
while (this.theadChildrenLength < displayTds + displayThs) {
TR.appendChild(document.createElement('TH'));
this.theadChildrenLength++;
}
while (this.theadChildrenLength > displayTds + displayThs) {
TR.removeChild(TR.lastChild);
this.theadChildrenLength--;
}
}
else if (TR) {
this.wtDom.empty(TR);
}
//draw COLGROUP
for (c = 0; c < this.colgroupChildrenLength; c++) {
if (c < displayThs) {
this.wtDom.addClass(this.COLGROUP.childNodes[c], 'rowHeader');
}
else {
this.wtDom.removeClass(this.COLGROUP.childNodes[c], 'rowHeader');
}
}
//draw THEAD
if (columnHeaders.length) {
TR = this.THEAD.firstChild;
if (displayThs) {
TD = TR.firstChild; //actually it is TH but let's reuse single variable
for (c = 0; c < displayThs; c++) {
rowHeaders[c](-displayThs + c, TD);
TD = TD.nextSibling;
}
}
}
for (c = 0; c < displayTds; c++) {
if (columnHeaders.length) {
columnHeaders[0](this.columnFilter.visibleToSource(c), TR.childNodes[displayThs + c]);
}
}
};
WalkontableTable.prototype.adjustColumns = function (TR, desiredCount) {
var count = TR.childNodes.length;
while (count < desiredCount) {
var TD = document.createElement('TD');
TR.appendChild(TD);
count++;
}
while (count > desiredCount) {
TR.removeChild(TR.lastChild);
count--;
}
};
WalkontableTable.prototype.draw = function (selectionsOnly) {
if (this.instance.getSetting('nativeScrollbars')) {
this.verticalRenderReverse = false; //this is only supported in dragdealer mode, not in native
}
this.rowFilter.readSettings(this.instance);
this.columnFilter.readSettings(this.instance);
if (!selectionsOnly) {
if (this.instance.getSetting('nativeScrollbars')) {
if (this.instance.cloneSource) {
this.tableOffset = this.instance.cloneSource.wtTable.tableOffset;
}
else {
this.holderOffset = this.wtDom.offset(this.holder);
this.tableOffset = this.wtDom.offset(this.TABLE);
this.instance.wtScrollbars.vertical.readWindowSize();
this.instance.wtScrollbars.horizontal.readWindowSize();
this.instance.wtViewport.resetSettings();
}
}
else {
this.tableOffset = this.wtDom.offset(this.TABLE);
this.instance.wtViewport.resetSettings();
}
this._doDraw();
}
else {
this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(true);
}
this.refreshPositions(selectionsOnly);
if (!selectionsOnly) {
if (this.instance.getSetting('nativeScrollbars')) {
if (!this.instance.cloneSource) {
this.instance.wtScrollbars.vertical.resetFixedPosition();
this.instance.wtScrollbars.horizontal.resetFixedPosition();
this.instance.wtScrollbars.corner.resetFixedPosition();
this.instance.wtScrollbars.debug && this.instance.wtScrollbars.debug.resetFixedPosition();
}
}
}
this.instance.drawn = true;
return this;
};
WalkontableTable.prototype._doDraw = function () {
var r = 0
, source_r
, c
, source_c
, offsetRow = this.instance.getSetting('offsetRow')
, totalRows = this.instance.getSetting('totalRows')
, totalColumns = this.instance.getSetting('totalColumns')
, displayTds
, rowHeaders = this.instance.getSetting('rowHeaders')
, displayThs = rowHeaders.length
, TR
, TD
, TH
, adjusted = false
, workspaceWidth
, mustBeInViewport
, res;
if (this.verticalRenderReverse) {
mustBeInViewport = offsetRow;
}
var noPartial = false;
if (this.verticalRenderReverse) {
if (offsetRow === totalRows - this.rowFilter.fixedCount - 1) {
noPartial = true;
}
else {
this.instance.update('offsetRow', offsetRow + 1); //if we are scrolling reverse
this.rowFilter.readSettings(this.instance);
}
}
if (this.instance.cloneSource) {
this.columnStrategy = this.instance.cloneSource.wtTable.columnStrategy;
this.rowStrategy = this.instance.cloneSource.wtTable.rowStrategy;
}
//draw TBODY
if (totalColumns > 0) {
source_r = this.rowFilter.visibleToSource(r);
var fixedRowsTop = this.instance.getSetting('fixedRowsTop');
var cloneLimit;
if (this.instance.cloneSource) { //must be run after adjustAvailableNodes because otherwise this.rowStrategy is not yet defined
if (this.instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
cloneLimit = fixedRowsTop;
}
else if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative) {
cloneLimit = this.rowStrategy.countVisible();
}
//else if WalkontableDebugOverlay do nothing. No cloneLimit means render ALL rows
}
this.adjustAvailableNodes();
adjusted = true;
if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) {
displayTds = this.instance.getSetting('fixedColumnsLeft');
}
else {
displayTds = this.columnStrategy.cellCount;
}
if (!this.instance.cloneSource) {
workspaceWidth = this.instance.wtViewport.getWorkspaceWidth();
this.columnStrategy.stretch();
}
for (c = 0; c < displayTds; c++) {
this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px';
}
while (source_r < totalRows && source_r >= 0) {
if (r > 1000) {
throw new Error('Security brake: Too much TRs. Please define height for your table, which will enforce scrollbars.');
}
if (cloneLimit !== void 0 && r === cloneLimit) {
break; //we have as much rows as needed for this clone
}
if (r >= this.tbodyChildrenLength || (this.verticalRenderReverse && r >= this.rowFilter.fixedCount)) {
TR = document.createElement('TR');
for (c = 0; c < displayThs; c++) {
TR.appendChild(document.createElement('TH'));
}
if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) {
this.TBODY.insertBefore(TR, this.TBODY.childNodes[this.rowFilter.fixedCount] || this.TBODY.firstChild);
}
else {
this.TBODY.appendChild(TR);
}
this.tbodyChildrenLength++;
}
else if (r === 0) {
TR = this.TBODY.firstChild;
}
else {
TR = TR.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
//TH
TH = TR.firstChild;
for (c = 0; c < displayThs; c++) {
//If the number of row headers increased we need to replace TD with TH
if (TH.nodeName == 'TD') {
TD = TH;
TH = document.createElement('TH');
TR.insertBefore(TH, TD);
TR.removeChild(TD);
}
rowHeaders[c](source_r, TH); //actually TH
TH = TH.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
this.adjustColumns(TR, displayTds + displayThs);
for (c = 0; c < displayTds; c++) {
source_c = this.columnFilter.visibleToSource(c);
if (c === 0) {
TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(source_c)];
}
else {
TD = TD.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
//If the number of headers has been reduced, we need to replace excess TH with TD
if (TD.nodeName == 'TH') {
TH = TD;
TD = document.createElement('TD');
TR.insertBefore(TD, TH);
TR.removeChild(TH);
}
TD.className = '';
TD.removeAttribute('style');
this.instance.getSetting('cellRenderer', source_r, source_c, TD);
}
offsetRow = this.instance.getSetting('offsetRow'); //refresh the value
//after last column is rendered, check if last cell is fully displayed
if (this.verticalRenderReverse && noPartial) {
if (-this.wtDom.outerHeight(TR.firstChild) < this.rowStrategy.remainingSize) {
this.TBODY.removeChild(TR);
this.instance.update('offsetRow', offsetRow + 1);
this.tbodyChildrenLength--;
this.rowFilter.readSettings(this.instance);
break;
}
else if (!this.instance.cloneSource) {
res = this.rowStrategy.add(r, TD, this.verticalRenderReverse);
if (res === false) {
this.rowStrategy.removeOutstanding();
}
}
}
else if (!this.instance.cloneSource) {
res = this.rowStrategy.add(r, TD, this.verticalRenderReverse);
if (res === false) {
if (!this.instance.getSetting('nativeScrollbars')) {
this.rowStrategy.removeOutstanding();
}
}
if (this.rowStrategy.isLastIncomplete()) {
if (this.verticalRenderReverse && !this.isRowInViewport(mustBeInViewport)) {
//we failed because one of the cells was by far too large. Recover by rendering from top
this.verticalRenderReverse = false;
this.instance.update('offsetRow', mustBeInViewport);
this.draw();
return;
}
break;
}
}
if (this.instance.getSetting('nativeScrollbars')) {
if (this.instance.cloneSource) {
TR.style.height = this.instance.getSetting('rowHeight', source_r) + 'px'; //if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is the way to make sure that the overlay will has same row height
}
else {
this.instance.getSetting('rowHeight', source_r, TD); //this trick saves rowHeight in rowHeightCache. It is then read in WalkontableVerticalScrollbarNative.prototype.sumCellSizes and reset in Walkontable constructor
}
}
if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) {
if (offsetRow === 0) {
break;
}
this.instance.update('offsetRow', offsetRow - 1);
this.rowFilter.readSettings(this.instance);
}
else {
r++;
}
source_r = this.rowFilter.visibleToSource(r);
}
}
if (!adjusted) {
this.adjustAvailableNodes();
}
if (!(this.instance.cloneOverlay instanceof WalkontableDebugOverlay)) {
r = this.rowStrategy.countVisible();
while (this.tbodyChildrenLength > r) {
this.TBODY.removeChild(this.TBODY.lastChild);
this.tbodyChildrenLength--;
}
}
this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(false);
if (!this.instance.cloneSource) {
if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) {
//workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching
this.columnStrategy.stretch();
for (c = 0; c < this.columnStrategy.cellCount; c++) {
this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px';
}
}
}
this.verticalRenderReverse = false;
};
WalkontableTable.prototype.refreshPositions = function (selectionsOnly) {
this.refreshHiderDimensions();
this.refreshSelections(selectionsOnly);
};
WalkontableTable.prototype.refreshSelections = function (selectionsOnly) {
var vr
, r
, vc
, c
, s
, slen
, classNames = []
, visibleRows = this.rowStrategy.countVisible()
, visibleColumns = this.columnStrategy.countVisible();
this.oldCellCache = this.currentCellCache;
this.currentCellCache = new WalkontableClassNameCache();
if (this.instance.selections) {
for (r in this.instance.selections) {
if (this.instance.selections.hasOwnProperty(r)) {
this.instance.selections[r].draw();
if (this.instance.selections[r].settings.className) {
classNames.push(this.instance.selections[r].settings.className);
}
if (this.instance.selections[r].settings.highlightRowClassName) {
classNames.push(this.instance.selections[r].settings.highlightRowClassName);
}
if (this.instance.selections[r].settings.highlightColumnClassName) {
classNames.push(this.instance.selections[r].settings.highlightColumnClassName);
}
}
}
}
slen = classNames.length;
for (vr = 0; vr < visibleRows; vr++) {
for (vc = 0; vc < visibleColumns; vc++) {
r = this.rowFilter.visibleToSource(vr);
c = this.columnFilter.visibleToSource(vc);
for (s = 0; s < slen; s++) {
if (this.currentCellCache.test(vr, vc, classNames[s])) {
this.wtDom.addClass(this.getCell([r, c]), classNames[s]);
}
else if (selectionsOnly && this.oldCellCache.test(vr, vc, classNames[s])) {
this.wtDom.removeClass(this.getCell([r, c]), classNames[s]);
}
}
}
}
};
/**
* getCell
* @param {Array} coords
* @return {Object} HTMLElement on success or {Number} one of the exit codes on error:
* -1 row before viewport
* -2 row after viewport
* -3 column before viewport
* -4 column after viewport
*
*/
WalkontableTable.prototype.getCell = function (coords) {
if (this.isRowBeforeViewport(coords[0])) {
return -1; //row before viewport
}
else if (this.isRowAfterViewport(coords[0])) {
return -2; //row after viewport
}
else {
if (this.isColumnBeforeViewport(coords[1])) {
return -3; //column before viewport
}
else if (this.isColumnAfterViewport(coords[1])) {
return -4; //column after viewport
}
else {
return this.TBODY.childNodes[this.rowFilter.sourceToVisible(coords[0])].childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords[1])];
}
}
};
WalkontableTable.prototype.getCoords = function (TD) {
return [
this.rowFilter.visibleToSource(this.wtDom.index(TD.parentNode)),
this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex)
];
};
//returns -1 if no row is visible
WalkontableTable.prototype.getLastVisibleRow = function () {
return this.rowFilter.visibleToSource(this.rowStrategy.cellCount - 1);
};
//returns -1 if no column is visible
WalkontableTable.prototype.getLastVisibleColumn = function () {
return this.columnFilter.visibleToSource(this.columnStrategy.cellCount - 1);
};
WalkontableTable.prototype.isRowBeforeViewport = function (r) {
return (this.rowFilter.sourceToVisible(r) < this.rowFilter.fixedCount && r >= this.rowFilter.fixedCount);
};
WalkontableTable.prototype.isRowAfterViewport = function (r) {
return (r > this.getLastVisibleRow());
};
WalkontableTable.prototype.isColumnBeforeViewport = function (c) {
return (this.columnFilter.sourceToVisible(c) < this.columnFilter.fixedCount && c >= this.columnFilter.fixedCount);
};
WalkontableTable.prototype.isColumnAfterViewport = function (c) {
return (c > this.getLastVisibleColumn());
};
WalkontableTable.prototype.isRowInViewport = function (r) {
return (!this.isRowBeforeViewport(r) && !this.isRowAfterViewport(r));
};
WalkontableTable.prototype.isColumnInViewport = function (c) {
return (!this.isColumnBeforeViewport(c) && !this.isColumnAfterViewport(c));
};
WalkontableTable.prototype.isLastRowFullyVisible = function () {
return (this.getLastVisibleRow() === this.instance.getSetting('totalRows') - 1 && !this.rowStrategy.isLastIncomplete());
};
WalkontableTable.prototype.isLastColumnFullyVisible = function () {
return (this.getLastVisibleColumn() === this.instance.getSetting('totalColumns') - 1 && !this.columnStrategy.isLastIncomplete());
};
function WalkontableViewport(instance) {
this.instance = instance;
this.resetSettings();
if (this.instance.getSetting('nativeScrollbars')) {
var that = this;
$(window).on('resize', function () {
that.clientHeight = that.getWorkspaceHeight();
});
}
}
/*WalkontableViewport.prototype.isInSightVertical = function () {
//is table outside viewport bottom edge
if (tableTop > windowHeight + scrollTop) {
return -1;
}
//is table outside viewport top edge
else if (scrollTop > tableTop + tableFakeHeight) {
return -2;
}
//table is in viewport but how much exactly?
else {
}
};*/
//used by scrollbar
WalkontableViewport.prototype.getWorkspaceHeight = function (proposedHeight) {
if (this.instance.getSetting('nativeScrollbars')) {
return this.instance.wtScrollbars.vertical.windowSize;
}
var height = this.instance.getSetting('height');
if (height === Infinity || height === void 0 || height === null || height < 1) {
if (this.instance.wtScrollbars.vertical instanceof WalkontableOverlay) {
height = this.instance.wtScrollbars.vertical.availableSize();
}
else {
height = Infinity;
}
}
if (height !== Infinity) {
if (proposedHeight >= height) {
height -= this.instance.getSetting('scrollbarHeight');
}
else if (this.instance.wtScrollbars.horizontal.visible) {
height -= this.instance.getSetting('scrollbarHeight');
}
}
return height;
};
WalkontableViewport.prototype.getWorkspaceWidth = function (proposedWidth) {
var width = this.instance.getSetting('width');
if (width === Infinity || width === void 0 || width === null || width < 1) {
if (this.instance.wtScrollbars.horizontal instanceof WalkontableOverlay) {
width = this.instance.wtScrollbars.horizontal.availableSize();
}
else {
width = Infinity;
}
}
if (width !== Infinity) {
if (proposedWidth >= width) {
width -= this.instance.getSetting('scrollbarWidth');
}
else if (this.instance.wtScrollbars.vertical.visible) {
width -= this.instance.getSetting('scrollbarWidth');
}
}
return width;
};
WalkontableViewport.prototype.getWorkspaceActualHeight = function () {
return this.instance.wtDom.outerHeight(this.instance.wtTable.TABLE);
};
WalkontableViewport.prototype.getWorkspaceActualWidth = function () {
return this.instance.wtDom.outerWidth(this.instance.wtTable.TABLE) || this.instance.wtDom.outerWidth(this.instance.wtTable.TBODY) || this.instance.wtDom.outerWidth(this.instance.wtTable.THEAD); //IE8 reports 0 as <table> offsetWidth;
};
WalkontableViewport.prototype.getColumnHeaderHeight = function () {
if (isNaN(this.columnHeaderHeight)) {
var cellOffset = this.instance.wtDom.offset(this.instance.wtTable.TBODY)
, tableOffset = this.instance.wtTable.tableOffset;
this.columnHeaderHeight = cellOffset.top - tableOffset.top;
}
return this.columnHeaderHeight;
};
WalkontableViewport.prototype.getViewportHeight = function (proposedHeight) {
var containerHeight = this.getWorkspaceHeight(proposedHeight);
if (containerHeight === Infinity) {
return containerHeight;
}
var columnHeaderHeight = this.getColumnHeaderHeight();
if (columnHeaderHeight > 0) {
return containerHeight - columnHeaderHeight;
}
else {
return containerHeight;
}
};
WalkontableViewport.prototype.getRowHeaderWidth = function () {
if (this.instance.cloneSource) {
return this.instance.cloneSource.wtViewport.getRowHeaderWidth();
}
if (isNaN(this.rowHeaderWidth)) {
var rowHeaders = this.instance.getSetting('rowHeaders');
if (rowHeaders.length) {
var TH = this.instance.wtTable.TABLE.querySelector('TH');
this.rowHeaderWidth = 0;
for (var i = 0, ilen = rowHeaders.length; i < ilen; i++) {
if (TH) {
this.rowHeaderWidth += this.instance.wtDom.outerWidth(TH);
TH = TH.nextSibling;
}
else {
this.rowHeaderWidth += 50; //yes this is a cheat but it worked like that before, just taking assumption from CSS instead of measuring. TODO: proper fix
}
}
}
else {
this.rowHeaderWidth = 0;
}
}
return this.rowHeaderWidth;
};
WalkontableViewport.prototype.getViewportWidth = function (proposedWidth) {
var containerWidth = this.getWorkspaceWidth(proposedWidth);
if (containerWidth === Infinity) {
return containerWidth;
}
var rowHeaderWidth = this.getRowHeaderWidth();
if (rowHeaderWidth > 0) {
return containerWidth - rowHeaderWidth;
}
else {
return containerWidth;
}
};
WalkontableViewport.prototype.resetSettings = function () {
this.rowHeaderWidth = NaN;
this.columnHeaderHeight = NaN;
};
function WalkontableWheel(instance) {
if (instance.getSetting('nativeScrollbars')) {
return;
}
//spreader === instance.wtTable.TABLE.parentNode
$(instance.wtTable.spreader).on('mousewheel', function (event, delta, deltaX, deltaY) {
if (!deltaX && !deltaY && delta) { //we are in IE8, see https://github.com/brandonaaron/jquery-mousewheel/issues/53
deltaY = delta;
}
if (!deltaX && !deltaY) { //this happens in IE8 test case
return;
}
if (deltaY > 0 && instance.getSetting('offsetRow') === 0) {
return; //attempt to scroll up when it's already showing first row
}
else if (deltaY < 0 && instance.wtTable.isLastRowFullyVisible()) {
return; //attempt to scroll down when it's already showing last row
}
else if (deltaX < 0 && instance.getSetting('offsetColumn') === 0) {
return; //attempt to scroll left when it's already showing first column
}
else if (deltaX > 0 && instance.wtTable.isLastColumnFullyVisible()) {
return; //attempt to scroll right when it's already showing last column
}
//now we are sure we really want to scroll
clearTimeout(instance.wheelTimeout);
instance.wheelTimeout = setTimeout(function () { //timeout is needed because with fast-wheel scrolling mousewheel event comes dozen times per second
if (deltaY) {
//ceil is needed because jquery-mousewheel reports fractional mousewheel deltas on touchpad scroll
//see http://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers
if (instance.wtScrollbars.vertical.visible) { // if we see scrollbar
instance.scrollVertical(-Math.ceil(deltaY)).draw();
}
}
else if (deltaX) {
if (instance.wtScrollbars.horizontal.visible) { // if we see scrollbar
instance.scrollHorizontal(Math.ceil(deltaX)).draw();
}
}
}, 0);
event.preventDefault();
});
}
/**
* Dragdealer JS v0.9.5 - patched by Walkontable at lines 66, 309-310, 339-340
* http://code.ovidiu.ch/dragdealer-js
*
* Copyright (c) 2010, Ovidiu Chereches
* MIT License
* http://legal.ovidiu.ch/licenses/MIT
*/
/* Cursor */
var Cursor =
{
x: 0, y: 0,
init: function()
{
this.setEvent('mouse');
this.setEvent('touch');
},
setEvent: function(type)
{
var moveHandler = document['on' + type + 'move'] || function(){};
document['on' + type + 'move'] = function(e)
{
moveHandler(e);
Cursor.refresh(e);
}
},
refresh: function(e)
{
if(!e)
{
e = window.event;
}
if(e.type == 'mousemove')
{
this.set(e);
}
else if(e.touches)
{
this.set(e.touches[0]);
}
},
set: function(e)
{
if(e.pageX || e.pageY)
{
this.x = e.pageX;
this.y = e.pageY;
}
else if(document.body && (e.clientX || e.clientY)) //need to check whether body exists, because of IE8 issue (#1084)
{
this.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
this.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
}
};
Cursor.init();
/* Position */
var Position =
{
get: function(obj)
{
var curtop = 0, curleft = 0; //Walkontable patch. Original (var curleft = curtop = 0;) created curtop in global scope
if(obj.offsetParent)
{
do
{
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
while((obj = obj.offsetParent));
}
return [curleft, curtop];
}
};
/* Dragdealer */
var Dragdealer = function(wrapper, options)
{
if(typeof(wrapper) == 'string')
{
wrapper = document.getElementById(wrapper);
}
if(!wrapper)
{
return;
}
var handle = wrapper.getElementsByTagName('div')[0];
if(!handle || handle.className.search(/(^|\s)handle(\s|$)/) == -1)
{
return;
}
this.init(wrapper, handle, options || {});
this.setup();
};
Dragdealer.prototype =
{
init: function(wrapper, handle, options)
{
this.wrapper = wrapper;
this.handle = handle;
this.options = options;
this.disabled = this.getOption('disabled', false);
this.horizontal = this.getOption('horizontal', true);
this.vertical = this.getOption('vertical', false);
this.slide = this.getOption('slide', true);
this.steps = this.getOption('steps', 0);
this.snap = this.getOption('snap', false);
this.loose = this.getOption('loose', false);
this.speed = this.getOption('speed', 10) / 100;
this.xPrecision = this.getOption('xPrecision', 0);
this.yPrecision = this.getOption('yPrecision', 0);
this.callback = options.callback || null;
this.animationCallback = options.animationCallback || null;
this.bounds = {
left: options.left || 0, right: -(options.right || 0),
top: options.top || 0, bottom: -(options.bottom || 0),
x0: 0, x1: 0, xRange: 0,
y0: 0, y1: 0, yRange: 0
};
this.value = {
prev: [-1, -1],
current: [options.x || 0, options.y || 0],
target: [options.x || 0, options.y || 0]
};
this.offset = {
wrapper: [0, 0],
mouse: [0, 0],
prev: [-999999, -999999],
current: [0, 0],
target: [0, 0]
};
this.change = [0, 0];
this.activity = false;
this.dragging = false;
this.tapping = false;
},
getOption: function(name, defaultValue)
{
return this.options[name] !== undefined ? this.options[name] : defaultValue;
},
setup: function()
{
this.setWrapperOffset();
this.setBoundsPadding();
this.setBounds();
this.setSteps();
this.addListeners();
},
setWrapperOffset: function()
{
this.offset.wrapper = Position.get(this.wrapper);
},
setBoundsPadding: function()
{
if(!this.bounds.left && !this.bounds.right)
{
this.bounds.left = Position.get(this.handle)[0] - this.offset.wrapper[0];
this.bounds.right = -this.bounds.left;
}
if(!this.bounds.top && !this.bounds.bottom)
{
this.bounds.top = Position.get(this.handle)[1] - this.offset.wrapper[1];
this.bounds.bottom = -this.bounds.top;
}
},
setBounds: function()
{
this.bounds.x0 = this.bounds.left;
this.bounds.x1 = this.wrapper.offsetWidth + this.bounds.right;
this.bounds.xRange = (this.bounds.x1 - this.bounds.x0) - this.handle.offsetWidth;
this.bounds.y0 = this.bounds.top;
this.bounds.y1 = this.wrapper.offsetHeight + this.bounds.bottom;
this.bounds.yRange = (this.bounds.y1 - this.bounds.y0) - this.handle.offsetHeight;
this.bounds.xStep = 1 / (this.xPrecision || Math.max(this.wrapper.offsetWidth, this.handle.offsetWidth));
this.bounds.yStep = 1 / (this.yPrecision || Math.max(this.wrapper.offsetHeight, this.handle.offsetHeight));
},
setSteps: function()
{
if(this.steps > 1)
{
this.stepRatios = [];
for(var i = 0; i <= this.steps - 1; i++)
{
this.stepRatios[i] = i / (this.steps - 1);
}
}
},
addListeners: function()
{
var self = this;
this.wrapper.onselectstart = function()
{
return false;
}
this.handle.onmousedown = this.handle.ontouchstart = function(e)
{
self.handleDownHandler(e);
};
this.wrapper.onmousedown = this.wrapper.ontouchstart = function(e)
{
self.wrapperDownHandler(e);
};
var mouseUpHandler = document.onmouseup || function(){};
document.onmouseup = function(e)
{
mouseUpHandler(e);
self.documentUpHandler(e);
};
var touchEndHandler = document.ontouchend || function(){};
document.ontouchend = function(e)
{
touchEndHandler(e);
self.documentUpHandler(e);
};
var resizeHandler = window.onresize || function(){};
window.onresize = function(e)
{
resizeHandler(e);
self.documentResizeHandler(e);
};
this.wrapper.onmousemove = function(e)
{
self.activity = true;
}
this.wrapper.onclick = function(e)
{
return !self.activity;
}
this.interval = setInterval(function(){ self.animate() }, 25);
self.animate(false, true);
},
handleDownHandler: function(e)
{
this.activity = false;
Cursor.refresh(e);
this.preventDefaults(e, true);
this.startDrag();
},
wrapperDownHandler: function(e)
{
Cursor.refresh(e);
this.preventDefaults(e, true);
this.startTap();
},
documentUpHandler: function(e)
{
this.stopDrag();
this.stopTap();
},
documentResizeHandler: function(e)
{
this.setWrapperOffset();
this.setBounds();
this.update();
},
enable: function()
{
this.disabled = false;
this.handle.className = this.handle.className.replace(/\s?disabled/g, '');
},
disable: function()
{
this.disabled = true;
this.handle.className += ' disabled';
},
setStep: function(x, y, snap)
{
this.setValue(
this.steps && x > 1 ? (x - 1) / (this.steps - 1) : 0,
this.steps && y > 1 ? (y - 1) / (this.steps - 1) : 0,
snap
);
},
setValue: function(x, y, snap)
{
this.setTargetValue([x, y || 0]);
if(snap)
{
this.groupCopy(this.value.current, this.value.target);
}
},
startTap: function(target)
{
if(this.disabled)
{
return;
}
this.tapping = true;
this.setWrapperOffset();
this.setBounds();
if(target === undefined)
{
target = [
Cursor.x - this.offset.wrapper[0] - (this.handle.offsetWidth / 2),
Cursor.y - this.offset.wrapper[1] - (this.handle.offsetHeight / 2)
];
}
this.setTargetOffset(target);
},
stopTap: function()
{
if(this.disabled || !this.tapping)
{
return;
}
this.tapping = false;
this.setTargetValue(this.value.current);
this.result();
},
startDrag: function()
{
if(this.disabled)
{
return;
}
this.setWrapperOffset();
this.setBounds();
this.offset.mouse = [
Cursor.x - Position.get(this.handle)[0],
Cursor.y - Position.get(this.handle)[1]
];
this.dragging = true;
},
stopDrag: function()
{
if(this.disabled || !this.dragging)
{
return;
}
this.dragging = false;
var target = this.groupClone(this.value.current);
if(this.slide)
{
var ratioChange = this.change;
target[0] += ratioChange[0] * 4;
target[1] += ratioChange[1] * 4;
}
this.setTargetValue(target);
this.result();
},
feedback: function()
{
var value = this.value.current;
if(this.snap && this.steps > 1)
{
value = this.getClosestSteps(value);
}
if(!this.groupCompare(value, this.value.prev))
{
if(typeof(this.animationCallback) == 'function')
{
this.animationCallback(value[0], value[1]);
}
this.groupCopy(this.value.prev, value);
}
},
result: function()
{
if(typeof(this.callback) == 'function')
{
this.callback(this.value.target[0], this.value.target[1]);
}
},
animate: function(direct, first)
{
if(direct && !this.dragging)
{
return;
}
if(this.dragging)
{
var prevTarget = this.groupClone(this.value.target);
var offset = [
Cursor.x - this.offset.wrapper[0] - this.offset.mouse[0],
Cursor.y - this.offset.wrapper[1] - this.offset.mouse[1]
];
this.setTargetOffset(offset, this.loose);
this.change = [
this.value.target[0] - prevTarget[0],
this.value.target[1] - prevTarget[1]
];
}
if(this.dragging || first)
{
this.groupCopy(this.value.current, this.value.target);
}
if(this.dragging || this.glide() || first)
{
this.update();
this.feedback();
}
},
glide: function()
{
var diff = [
this.value.target[0] - this.value.current[0],
this.value.target[1] - this.value.current[1]
];
if(!diff[0] && !diff[1])
{
return false;
}
if(Math.abs(diff[0]) > this.bounds.xStep || Math.abs(diff[1]) > this.bounds.yStep)
{
this.value.current[0] += diff[0] * this.speed;
this.value.current[1] += diff[1] * this.speed;
}
else
{
this.groupCopy(this.value.current, this.value.target);
}
return true;
},
update: function()
{
if(!this.snap)
{
this.offset.current = this.getOffsetsByRatios(this.value.current);
}
else
{
this.offset.current = this.getOffsetsByRatios(
this.getClosestSteps(this.value.current)
);
}
this.show();
},
show: function()
{
if(!this.groupCompare(this.offset.current, this.offset.prev))
{
if(this.horizontal)
{
this.handle.style.left = String(this.offset.current[0]) + 'px';
}
if(this.vertical)
{
this.handle.style.top = String(this.offset.current[1]) + 'px';
}
this.groupCopy(this.offset.prev, this.offset.current);
}
},
setTargetValue: function(value, loose)
{
var target = loose ? this.getLooseValue(value) : this.getProperValue(value);
this.groupCopy(this.value.target, target);
this.offset.target = this.getOffsetsByRatios(target);
},
setTargetOffset: function(offset, loose)
{
var value = this.getRatiosByOffsets(offset);
var target = loose ? this.getLooseValue(value) : this.getProperValue(value);
this.groupCopy(this.value.target, target);
this.offset.target = this.getOffsetsByRatios(target);
},
getLooseValue: function(value)
{
var proper = this.getProperValue(value);
return [
proper[0] + ((value[0] - proper[0]) / 4),
proper[1] + ((value[1] - proper[1]) / 4)
];
},
getProperValue: function(value)
{
var proper = this.groupClone(value);
proper[0] = Math.max(proper[0], 0);
proper[1] = Math.max(proper[1], 0);
proper[0] = Math.min(proper[0], 1);
proper[1] = Math.min(proper[1], 1);
if((!this.dragging && !this.tapping) || this.snap)
{
if(this.steps > 1)
{
proper = this.getClosestSteps(proper);
}
}
return proper;
},
getRatiosByOffsets: function(group)
{
return [
this.getRatioByOffset(group[0], this.bounds.xRange, this.bounds.x0),
this.getRatioByOffset(group[1], this.bounds.yRange, this.bounds.y0)
];
},
getRatioByOffset: function(offset, range, padding)
{
return range ? (offset - padding) / range : 0;
},
getOffsetsByRatios: function(group)
{
return [
this.getOffsetByRatio(group[0], this.bounds.xRange, this.bounds.x0),
this.getOffsetByRatio(group[1], this.bounds.yRange, this.bounds.y0)
];
},
getOffsetByRatio: function(ratio, range, padding)
{
return Math.round(ratio * range) + padding;
},
getClosestSteps: function(group)
{
return [
this.getClosestStep(group[0]),
this.getClosestStep(group[1])
];
},
getClosestStep: function(value)
{
var k = 0;
var min = 1;
for(var i = 0; i <= this.steps - 1; i++)
{
if(Math.abs(this.stepRatios[i] - value) < min)
{
min = Math.abs(this.stepRatios[i] - value);
k = i;
}
}
return this.stepRatios[k];
},
groupCompare: function(a, b)
{
return a[0] == b[0] && a[1] == b[1];
},
groupCopy: function(a, b)
{
a[0] = b[0];
a[1] = b[1];
},
groupClone: function(a)
{
return [a[0], a[1]];
},
preventDefaults: function(e, selection)
{
if(!e)
{
e = window.event;
}
if(e.preventDefault)
{
e.preventDefault();
}
e.returnValue = false;
if(selection && document.selection)
{
document.selection.empty();
}
},
cancelEvent: function(e)
{
if(!e)
{
e = window.event;
}
if(e.stopPropagation)
{
e.stopPropagation();
}
e.cancelBubble = true;
}
};
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.1.3
*
* Requires: 1.2.2+
*/
(function (factory) {
if ( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS style for Browserify
module.exports = factory;
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
var lowestDelta, lowestDeltaXY;
if ( $.event.fixHooks ) {
for ( var i = toFix.length; i; ) {
$.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i = toBind.length; i; ) {
this.addEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i = toBind.length; i; ) {
this.removeEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event,
args = [].slice.call(arguments, 1),
delta = 0,
deltaX = 0,
deltaY = 0,
absDelta = 0,
absDeltaXY = 0,
fn;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
if ( orgEvent.detail ) { delta = orgEvent.detail * -1; }
// New school wheel delta (wheel event)
if ( orgEvent.deltaY ) {
deltaY = orgEvent.deltaY * -1;
delta = deltaY;
}
if ( orgEvent.deltaX ) {
deltaX = orgEvent.deltaX;
delta = deltaX * -1;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }
// Look for lowest delta to normalize the delta values
absDelta = Math.abs(delta);
if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }
// Get a whole value for the deltas
fn = delta > 0 ? 'floor' : 'ceil';
delta = Math[fn](delta / lowestDelta);
deltaX = Math[fn](deltaX / lowestDeltaXY);
deltaY = Math[fn](deltaY / lowestDeltaXY);
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
}));
})(jQuery, window, Handsontable);
// numeral.js
// version : 1.4.7
// author : Adam Draper
// license : MIT
// http://adamwdraper.github.com/Numeral-js/
(function () {
/************************************
Constants
************************************/
var numeral,
VERSION = '1.4.7',
// internal storage for language config files
languages = {},
currentLanguage = 'en',
zeroFormat = null,
// check for nodeJS
hasModule = (typeof module !== 'undefined' && module.exports);
/************************************
Constructors
************************************/
// Numeral prototype object
function Numeral (number) {
this._n = number;
}
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
* problems for accounting- and finance-related software.
*/
function toFixed (value, precision, optionals) {
var power = Math.pow(10, precision),
output;
// Multiply up by precision, round accurately, then divide and use native toFixed():
output = (Math.round(value * power) / power).toFixed(precision);
if (optionals) {
var optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
output = output.replace(optionalsRegExp, '');
}
return output;
}
/************************************
Formatting
************************************/
// determine what type of formatting we need to do
function formatNumeral (n, format) {
var output;
// figure out what kind of format we are dealing with
if (format.indexOf('$') > -1) { // currency!!!!!
output = formatCurrency(n, format);
} else if (format.indexOf('%') > -1) { // percentage
output = formatPercentage(n, format);
} else if (format.indexOf(':') > -1) { // time
output = formatTime(n, format);
} else { // plain ol' numbers or bytes
output = formatNumber(n, format);
}
// return string
return output;
}
// revert to number
function unformatNumeral (n, string) {
if (string.indexOf(':') > -1) {
n._n = unformatTime(string);
} else {
if (string === zeroFormat) {
n._n = 0;
} else {
var stringOriginal = string;
if (languages[currentLanguage].delimiters.decimal !== '.') {
string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.');
}
// see if abbreviations are there so that we can multiply to the correct number
var thousandRegExp = new RegExp(languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'),
millionRegExp = new RegExp(languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'),
billionRegExp = new RegExp(languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'),
trillionRegExp = new RegExp(languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
// see if bytes are there so that we can multiply to the correct number
var prefixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
bytesMultiplier = false;
for (var power = 0; power <= prefixes.length; power++) {
bytesMultiplier = (string.indexOf(prefixes[power]) > -1) ? Math.pow(1024, power + 1) : false;
if (bytesMultiplier) {
break;
}
}
// do some math to create our number
n._n = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * Number(((string.indexOf('(') > -1) ? '-' : '') + string.replace(/[^0-9\.-]+/g, ''));
// round if we are talking about bytes
n._n = (bytesMultiplier) ? Math.ceil(n._n) : n._n;
}
}
return n._n;
}
function formatCurrency (n, format) {
var prependSymbol = (format.indexOf('$') <= 1) ? true : false;
// remove $ for the moment
var space = '';
// check for space before or after currency
if (format.indexOf(' $') > -1) {
space = ' ';
format = format.replace(' $', '');
} else if (format.indexOf('$ ') > -1) {
space = ' ';
format = format.replace('$ ', '');
} else {
format = format.replace('$', '');
}
// format the number
var output = formatNumeral(n, format);
// position the symbol
if (prependSymbol) {
if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
output = output.split('');
output.splice(1, 0, languages[currentLanguage].currency.symbol + space);
output = output.join('');
} else {
output = languages[currentLanguage].currency.symbol + space + output;
}
} else {
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + languages[currentLanguage].currency.symbol);
output = output.join('');
} else {
output = output + space + languages[currentLanguage].currency.symbol;
}
}
return output;
}
function formatPercentage (n, format) {
var space = '';
// check for space before %
if (format.indexOf(' %') > -1) {
space = ' ';
format = format.replace(' %', '');
} else {
format = format.replace('%', '');
}
n._n = n._n * 100;
var output = formatNumeral(n, format);
if (output.indexOf(')') > -1 ) {
output = output.split('');
output.splice(-1, 0, space + '%');
output = output.join('');
} else {
output = output + space + '%';
}
return output;
}
function formatTime (n, format) {
var hours = Math.floor(n._n/60/60),
minutes = Math.floor((n._n - (hours * 60 * 60))/60),
seconds = Math.round(n._n - (hours * 60 * 60) - (minutes * 60));
return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds);
}
function unformatTime (string) {
var timeArray = string.split(':'),
seconds = 0;
// turn hours and minutes into seconds and add them all up
if (timeArray.length === 3) {
// hours
seconds = seconds + (Number(timeArray[0]) * 60 * 60);
// minutes
seconds = seconds + (Number(timeArray[1]) * 60);
// seconds
seconds = seconds + Number(timeArray[2]);
} else if (timeArray.lenght === 2) {
// minutes
seconds = seconds + (Number(timeArray[0]) * 60);
// seconds
seconds = seconds + Number(timeArray[1]);
}
return Number(seconds);
}
function formatNumber (n, format) {
var negP = false,
optDec = false,
abbr = '',
bytes = '',
ord = '',
abs = Math.abs(n._n);
// check if number is zero and a custom zero format has been set
if (n._n === 0 && zeroFormat !== null) {
return zeroFormat;
} else {
// see if we should use parentheses for negative number
if (format.indexOf('(') > -1) {
negP = true;
format = format.slice(1, -1);
}
// see if abbreviation is wanted
if (format.indexOf('a') > -1) {
// check for space before abbreviation
if (format.indexOf(' a') > -1) {
abbr = ' ';
format = format.replace(' a', '');
} else {
format = format.replace('a', '');
}
if (abs >= Math.pow(10, 12)) {
// trillion
abbr = abbr + languages[currentLanguage].abbreviations.trillion;
n._n = n._n / Math.pow(10, 12);
} else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9)) {
// billion
abbr = abbr + languages[currentLanguage].abbreviations.billion;
n._n = n._n / Math.pow(10, 9);
} else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6)) {
// million
abbr = abbr + languages[currentLanguage].abbreviations.million;
n._n = n._n / Math.pow(10, 6);
} else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3)) {
// thousand
abbr = abbr + languages[currentLanguage].abbreviations.thousand;
n._n = n._n / Math.pow(10, 3);
}
}
// see if we are formatting bytes
if (format.indexOf('b') > -1) {
// check for space before
if (format.indexOf(' b') > -1) {
bytes = ' ';
format = format.replace(' b', '');
} else {
format = format.replace('b', '');
}
var prefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
min,
max;
for (var power = 0; power <= prefixes.length; power++) {
min = Math.pow(1024, power);
max = Math.pow(1024, power+1);
if (n._n >= min && n._n < max) {
bytes = bytes + prefixes[power];
if (min > 0) {
n._n = n._n / min;
}
break;
}
}
}
// see if ordinal is wanted
if (format.indexOf('o') > -1) {
// check for space before
if (format.indexOf(' o') > -1) {
ord = ' ';
format = format.replace(' o', '');
} else {
format = format.replace('o', '');
}
ord = ord + languages[currentLanguage].ordinal(n._n);
}
if (format.indexOf('[.]') > -1) {
optDec = true;
format = format.replace('[.]', '.');
}
var w = n._n.toString().split('.')[0],
precision = format.split('.')[1],
thousands = format.indexOf(','),
d = '',
neg = false;
if (precision) {
if (precision.indexOf('[') > -1) {
precision = precision.replace(']', '');
precision = precision.split('[');
d = toFixed(n._n, (precision[0].length + precision[1].length), precision[1].length);
} else {
d = toFixed(n._n, precision.length);
}
w = d.split('.')[0];
if (d.split('.')[1].length) {
d = languages[currentLanguage].delimiters.decimal + d.split('.')[1];
} else {
d = '';
}
if (optDec && Number(d) === 0) {
d = '';
}
} else {
w = toFixed(n._n, null);
}
// format number
if (w.indexOf('-') > -1) {
w = w.slice(1);
neg = true;
}
if (thousands > -1) {
w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands);
}
if (format.indexOf('.') === 0) {
w = '';
}
return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : '');
}
}
/************************************
Top Level Functions
************************************/
numeral = function (input) {
if (numeral.isNumeral(input)) {
input = input.value();
} else if (!Number(input)) {
input = 0;
}
return new Numeral(Number(input));
};
// version number
numeral.version = VERSION;
// compare numeral object
numeral.isNumeral = function (obj) {
return obj instanceof Numeral;
};
// This function will load languages and then set the global language. If
// no arguments are passed in, it will simply return the current global
// language key.
numeral.language = function (key, values) {
if (!key) {
return currentLanguage;
}
if (key && !values) {
currentLanguage = key;
}
if (values || !languages[key]) {
loadLanguage(key, values);
}
return numeral;
};
numeral.language('en', {
delimiters: {
thousands: ',',
decimal: '.'
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal: function (number) {
var b = number % 10;
return (~~ (number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
},
currency: {
symbol: '$'
}
});
numeral.zeroFormat = function (format) {
if (typeof(format) === 'string') {
zeroFormat = format;
} else {
zeroFormat = null;
}
};
/************************************
Helpers
************************************/
function loadLanguage(key, values) {
languages[key] = values;
}
/************************************
Numeral Prototype
************************************/
numeral.fn = Numeral.prototype = {
clone : function () {
return numeral(this);
},
format : function (inputString) {
return formatNumeral(this, inputString ? inputString : numeral.defaultFormat);
},
unformat : function (inputString) {
return unformatNumeral(this, inputString ? inputString : numeral.defaultFormat);
},
value : function () {
return this._n;
},
valueOf : function () {
return this._n;
},
set : function (value) {
this._n = Number(value);
return this;
},
add : function (value) {
this._n = this._n + Number(value);
return this;
},
subtract : function (value) {
this._n = this._n - Number(value);
return this;
},
multiply : function (value) {
this._n = this._n * Number(value);
return this;
},
divide : function (value) {
this._n = this._n / Number(value);
return this;
},
difference : function (value) {
var difference = this._n - Number(value);
if (difference < 0) {
difference = -difference;
}
return difference;
}
};
/************************************
Exposing Numeral
************************************/
// CommonJS module is defined
if (hasModule) {
module.exports = numeral;
}
/*global ender:false */
if (typeof ender === 'undefined') {
// here, `this` means `window` in the browser, or `global` on the server
// add `numeral` as a global object via a string identifier,
// for Closure Compiler 'advanced' mode
this['numeral'] = numeral;
}
/*global define:false */
if (typeof define === 'function' && define.amd) {
define([], function () {
return numeral;
});
}
}).call(this);
|
src/mixins/helpers.js | sanbornmedia/react-slick | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import {getTrackCSS, getTrackLeft, getTrackAnimateCSS, round} from './trackHelper';
import assign from 'object-assign';
var helpers = {
initialize: function (props) {
const slickList = ReactDOM.findDOMNode(this.list);
var slideCount = React.Children.count(props.children);
var listWidth = this.getWidth(slickList);
var trackWidth = this.getWidth(ReactDOM.findDOMNode(this.track));
var slideWidth;
if (!props.vertical) {
var centerPaddingAdj = props.centerMode && (parseInt(props.centerPadding) * 2);
slideWidth = round((this.getWidth(ReactDOM.findDOMNode(this)) - centerPaddingAdj)/props.slidesToShow);
} else {
slideWidth = round(this.getWidth(ReactDOM.findDOMNode(this)));
}
const slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]'));
const listHeight = slideHeight * props.slidesToShow;
var currentSlide = props.rtl ? slideCount - 1 - props.initialSlide : props.initialSlide;
this.setState({
slideCount,
slideWidth,
listWidth,
trackWidth,
currentSlide,
slideHeight,
listHeight,
}, function () {
var targetLeft = getTrackLeft(assign({
slideIndex: this.state.currentSlide,
trackRef: this.track
}, props, this.state));
// getCSS function needs previously set state
var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state));
this.setState({trackStyle: trackStyle});
this.autoPlay(); // once we're set up, trigger the initial autoplay.
});
},
update: function (props) {
const slickList = ReactDOM.findDOMNode(this.list);
// This method has mostly same code as initialize method.
// Refactor it
var slideCount = React.Children.count(props.children);
var listWidth = this.getWidth(slickList);
var trackWidth = this.getWidth(ReactDOM.findDOMNode(this.track));
var slideWidth;
if (!props.vertical) {
var centerPaddingAdj = props.centerMode && (parseInt(props.centerPadding) * 2);
slideWidth = round((this.getWidth(ReactDOM.findDOMNode(this)) - centerPaddingAdj)/props.slidesToShow);
} else {
slideWidth = round(this.getWidth(ReactDOM.findDOMNode(this)));
}
const slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]'));
const listHeight = slideHeight * props.slidesToShow;
// pause slider if autoplay is set to false
if(!props.autoplay) {
this.pause();
} else {
this.autoPlay();
}
this.setState({
slideCount,
slideWidth,
listWidth,
trackWidth,
slideHeight,
listHeight,
}, function () {
var targetLeft = getTrackLeft(assign({
slideIndex: this.state.currentSlide,
trackRef: this.track
}, props, this.state));
// getCSS function needs previously set state
var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state));
this.setState({trackStyle: trackStyle});
});
},
getWidth: function getWidth(elem) {
return elem.getBoundingClientRect().width || elem.offsetWidth || 0;
},
getHeight(elem) {
return elem.getBoundingClientRect().height || elem.offsetHeight || 0;
},
adaptHeight: function () {
if (this.props.adaptiveHeight) {
var selector = '[data-index="' + this.state.currentSlide +'"]';
if (this.list) {
var slickList = ReactDOM.findDOMNode(this.list);
slickList.style.height = slickList.querySelector(selector).offsetHeight + 'px';
}
}
},
canGoNext: function (opts){
var canGo = true;
if (!opts.infinite) {
if (opts.centerMode) {
// check if current slide is last slide
if (opts.currentSlide >= (opts.slideCount - 1)) {
canGo = false;
}
} else {
// check if all slides are shown in slider
if (opts.slideCount <= opts.slidesToShow ||
opts.currentSlide >= (opts.slideCount - opts.slidesToShow)) {
canGo = false;
}
}
}
return canGo;
},
slideHandler: function (index) {
// Functionality of animateSlide and postSlide is merged into this function
// console.log('slideHandler', index);
var targetSlide, currentSlide;
var targetLeft, currentLeft;
var callback;
if (this.props.waitForAnimate && this.state.animating) {
return;
}
if (this.props.fade) {
currentSlide = this.state.currentSlide;
// Don't change slide if it's not infite and current slide is the first or last slide.
if(this.props.infinite === false &&
(index < 0 || index >= this.state.slideCount)) {
return;
}
// Shifting targetSlide back into the range
if (index < 0) {
targetSlide = index + this.state.slideCount;
} else if (index >= this.state.slideCount) {
targetSlide = index - this.state.slideCount;
} else {
targetSlide = index;
}
if (this.props.lazyLoad && this.state.lazyLoadedList.indexOf(targetSlide) < 0) {
this.setState({
lazyLoadedList: this.state.lazyLoadedList.concat(targetSlide)
});
}
callback = () => {
this.setState({
animating: false
});
if (this.props.afterChange) {
this.props.afterChange(targetSlide);
}
delete this.animationEndCallback;
};
this.setState({
animating: true,
currentSlide: targetSlide
}, function () {
this.animationEndCallback = setTimeout(callback, this.props.speed);
});
if (this.props.beforeChange) {
this.props.beforeChange(this.state.currentSlide, targetSlide);
}
this.autoPlay();
return;
}
targetSlide = index;
if (targetSlide < 0) {
if(this.props.infinite === false) {
currentSlide = 0;
} else if (this.state.slideCount % this.props.slidesToScroll !== 0) {
currentSlide = this.state.slideCount - (this.state.slideCount % this.props.slidesToScroll);
} else {
currentSlide = this.state.slideCount + targetSlide;
}
} else if (targetSlide >= this.state.slideCount) {
if(this.props.infinite === false) {
currentSlide = this.state.slideCount - this.props.slidesToShow;
} else if (this.state.slideCount % this.props.slidesToScroll !== 0) {
currentSlide = 0;
} else {
currentSlide = targetSlide - this.state.slideCount;
}
} else {
currentSlide = targetSlide;
}
targetLeft = getTrackLeft(assign({
slideIndex: targetSlide,
trackRef: this.track
}, this.props, this.state));
currentLeft = getTrackLeft(assign({
slideIndex: currentSlide,
trackRef: this.track
}, this.props, this.state));
if (this.props.infinite === false) {
targetLeft = currentLeft;
}
if (this.props.beforeChange) {
this.props.beforeChange(this.state.currentSlide, currentSlide);
}
if (this.props.lazyLoad) {
var loaded = true;
var slidesToLoad = [];
for (var i = targetSlide; i < targetSlide + this.props.slidesToShow; i++ ) {
loaded = loaded && (this.state.lazyLoadedList.indexOf(i) >= 0);
if (!loaded) {
slidesToLoad.push(i);
}
}
if (!loaded) {
this.setState({
lazyLoadedList: this.state.lazyLoadedList.concat(slidesToLoad)
});
}
}
// Slide Transition happens here.
// animated transition happens to target Slide and
// non - animated transition happens to current Slide
// If CSS transitions are false, directly go the current slide.
if (this.props.useCSS === false) {
this.setState({
currentSlide: currentSlide,
trackStyle: getTrackCSS(assign({left: currentLeft}, this.props, this.state))
}, function () {
if (this.props.afterChange) {
this.props.afterChange(currentSlide);
}
});
} else {
var nextStateChanges = {
animating: false,
currentSlide: currentSlide,
trackStyle: getTrackCSS(assign({left: currentLeft}, this.props, this.state)),
swipeLeft: null
};
callback = () => {
this.setState(nextStateChanges);
if (this.props.afterChange) {
this.props.afterChange(currentSlide);
}
delete this.animationEndCallback;
};
this.setState({
animating: true,
currentSlide: currentSlide,
trackStyle: getTrackAnimateCSS(assign({left: targetLeft}, this.props, this.state))
}, function () {
this.animationEndCallback = setTimeout(callback, this.props.speed);
});
}
this.autoPlay();
},
swipeDirection: function (touchObject) {
var xDist, yDist, r, swipeAngle;
xDist = touchObject.startX - touchObject.curX;
yDist = touchObject.startY - touchObject.curY;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round(r * 180 / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if ((swipeAngle <= 45) && (swipeAngle >= 0) || (swipeAngle <= 360) && (swipeAngle >= 315)) {
return (this.props.rtl === false ? 'left' : 'right');
}
if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
return (this.props.rtl === false ? 'right' : 'left');
}
if (this.props.verticalSwiping === true) {
if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
return 'down';
} else {
return 'up';
}
}
return 'vertical';
},
play: function(){
var nextIndex;
if (!this.state.mounted) {
return false
}
if (this.props.rtl) {
nextIndex = this.state.currentSlide - this.props.slidesToScroll;
} else {
if (this.canGoNext(Object.assign({}, this.props,this.state))) {
nextIndex = this.state.currentSlide + this.props.slidesToScroll;
} else {
return false;
}
}
this.slideHandler(nextIndex);
},
autoPlay: function () {
if (this.state.autoPlayTimer) {
clearTimeout(this.state.autoPlayTimer);
}
if (this.props.autoplay) {
this.setState({
autoPlayTimer: setTimeout(this.play, this.props.autoplaySpeed)
});
}
},
pause: function () {
if (this.state.autoPlayTimer) {
clearTimeout(this.state.autoPlayTimer);
this.setState({
autoPlayTimer: null
});
}
}
};
export default helpers;
|
app/components/template/RatingInput.js | jendela/jendela | import React from 'react'
import { m } from '../../helper'
import Colors from '../../constants/JendelaColors'
const styles = {
rating: {
paddingTop: 0,
color: Colors.blue
}
}
const description = {
1: "Sangat Jelek",
2: "Jelek",
3: "Normal",
4: "Baik",
5: "Sangat Baik"
}
class Rating extends React.Component {
constructor(props) {
super(props)
this.state = {
star: 3,
description: ""
}
}
_onClick(star) {
this.setState({star: star})
if (this.props.onChange)
this.props.onChange(star)
}
_onMouseOver(star) {
this.setState({description: description[star]})
}
_onMouseOut() {
this.setState({description: ""})
}
render() {
const { size } = this.props
let starsSelect = [];
for (var i = 0; i < this.state.star; i++) {
starsSelect.push(<span key={i+1} style={m(styles.rating, { fontSize: size, cursor: "pointer" })}
onClick={this._onClick.bind(this, i+1)}>{'★'}</span>)
}
let stars = [];
for (var i = this.state.star; i < 5; i++) {
stars.push(<span key={i+1} style={m(styles.rating, { fontSize: size, cursor: "pointer", color: '#E0E0E0' })}
onClick={this._onClick.bind(this, i+1)}>{'★'}</span>)
}
return (
<span>
{starsSelect}
{stars}
</span>
)
}
}
Rating.defaultProps = {rating: 0, size: "1.4em"};
export default Rating
|
client/src/app/install/install-completed.js | opensupports/opensupports | import React from 'react';
import store from 'app/store';
import ConfigActions from 'actions/config-actions';
import i18n from 'lib-app/i18n';
import Message from 'core-components/message';
class InstallCompleted extends React.Component {
componentDidMount() {
store.dispatch(ConfigActions.init());
setTimeout(() => {
store.dispatch(ConfigActions.checkInstallation());
}, 3000);
}
render() {
return (
<div className="install-completed">
<Message showCloseButton={false} title={i18n('INSTALLATION_COMPLETED_TITLE')} type="success">
{i18n('INSTALLATION_COMPLETED_DESCRIPTION')}
</Message>
</div>
);
}
}
export default InstallCompleted;
|
newclient/scripts/components/user/progress-bar/index.js | kuali/research-coi | /* @flow */
/*
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 React from 'react';
import {merge} from '../../merge';
export function ProgressBar(props, {configState}) {
const styles = {
container: {
width: '100%',
height: 15
},
bar: {
width: `${props.percentage}%`,
backgroundColor: configState.config.colors.two,
height: '100%',
transition: 'width .2s ease-in-out'
}
};
return (
<div style={merge(styles.container, props.style)} onClick={props.onClick}>
<div style={styles.bar} />
</div>
);
}
ProgressBar.contextTypes = {
configState: React.PropTypes.object
};
|
Components/Core.PeoplePicker/Core.PeoplePickerWeb/Scripts/jquery-1.9.1.min.js | Claire-Hindhaugh/PnP | /* NUGET: BEGIN LICENSE TEXT
jQuery v1.9.1
Microsoft grants you the right to use these script files for the sole purpose of either: (i) interacting through your browser with the Microsoft website, subject to the website's terms of use; or (ii) using the files as included with a Microsoft product subject to that product's license terms. Microsoft reserves all other rights to the files not expressly granted by Microsoft, whether by implication, estoppel or otherwise. The notices and licenses below are for informational purposes only.
***************************************************
* jQuery JavaScript Library v1.9.1
* http://jquery.com/
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
********************************
* Includes Sizzle CSS Selector Engine
* http://sizzlejs.com/
* Copyright 2012 jQuery Foundation and other contributors
********************************************************
Provided for Informational Purposes Only
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* NUGET: END LICENSE TEXT */
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,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%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):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){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;
return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.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])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.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){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.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"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&>(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={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:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l)
}b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.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){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,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"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.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),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window); |
src/svg-icons/action/info-outline.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionInfoOutline = (props) => (
<SvgIcon {...props}>
<path d="M11 17h2v-6h-2v6zm1-15C6.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 8zM11 9h2V7h-2v2z"/>
</SvgIcon>
);
ActionInfoOutline = pure(ActionInfoOutline);
ActionInfoOutline.displayName = 'ActionInfoOutline';
ActionInfoOutline.muiName = 'SvgIcon';
export default ActionInfoOutline;
|
app/packs/src/components/ReactionDetailsContainers.js | ComPlat/chemotion_ELN | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
PanelGroup,
Panel,
Button,
OverlayTrigger, SplitButton, ButtonGroup, MenuItem, Tooltip
} from 'react-bootstrap';
import Container from './models/Container';
import ContainerComponent from './ContainerComponent';
import PrintCodeButton from './common/PrintCodeButton';
import QuillViewer from './QuillViewer';
import ImageModal from './common/ImageModal';
import { hNmrCount, cNmrCount, instrumentText } from './utils/ElementUtils';
import { contentToText } from './utils/quillFormat';
import { chmoConversions } from './OlsComponent';
import { previewContainerImage } from './utils/imageHelper';
import { JcampIds, BuildSpcInfos } from './utils/SpectraHelper';
import UIStore from './stores/UIStore';
import SpectraActions from './actions/SpectraActions';
import LoadingActions from './actions/LoadingActions';
import ViewSpectra from './ViewSpectra';
import TextTemplateActions from './actions/TextTemplateActions';
const nmrMsg = (reaction, container) => {
if (container.extended_metadata &&
(typeof container.extended_metadata.kind === 'undefined' ||
(container.extended_metadata.kind.split('|')[0].trim() !== chmoConversions.nmr_1h.termId && container.extended_metadata.kind.split('|')[0].trim() !== chmoConversions.nmr_13c.termId)
)) {
return '';
}
const nmrStr = container.extended_metadata && contentToText(container.extended_metadata.content);
if ((container.extended_metadata.kind || '').split('|')[0].trim() === chmoConversions.nmr_1h.termId) {
const msg = hNmrCount(nmrStr);
return (<div style={{ display: 'inline', color: 'black' }}> (<sup>1</sup>H: {msg})</div>);
} else if ((container.extended_metadata.kind || '').split('|')[0].trim() === chmoConversions.nmr_13c.termId) {
const msg = cNmrCount(nmrStr);
return (<div style={{ display: 'inline', color: 'black' }}> (<sup>13</sup>C: {msg})</div>);
}
};
const SpectraEditorBtn = ({
element, spcInfo, hasJcamp, hasChemSpectra,
toggleSpectraModal, confirmRegenerate,
}) => (
<OverlayTrigger
placement="bottom"
delayShow={500}
overlay={<Tooltip id="spectra">Spectra Editor {!spcInfo ? ': Reprocess' : ''}</Tooltip>}
>{spcInfo ? (
<ButtonGroup className="button-right">
<SplitButton
id="spectra-editor-split-button"
pullRight
bsStyle="info"
bsSize="xsmall"
title={<i className="fa fa-area-chart" />}
onToggle={(open, event) => { if (event) { event.stopPropagation(); } }}
onClick={toggleSpectraModal}
disabled={!spcInfo || !hasChemSpectra}
>
<MenuItem
id="regenerate-spectra"
key="regenerate-spectra"
onSelect={(eventKey, event) => {
event.stopPropagation();
confirmRegenerate(event);
}}
disabled={!hasJcamp || !element.can_update}
>
<i className="fa fa-refresh" /> Reprocess
</MenuItem>
</SplitButton>
</ButtonGroup>
) : (
<Button
bsStyle="warning"
bsSize="xsmall"
className="button-right"
onClick={confirmRegenerate}
disabled={false}
>
<i className="fa fa-area-chart" /><i className="fa fa-refresh " />
</Button>
)}
</OverlayTrigger>
);
SpectraEditorBtn.propTypes = {
element: PropTypes.object,
hasJcamp: PropTypes.bool,
spcInfo: PropTypes.oneOfType([
PropTypes.object,
PropTypes.bool,
]),
hasChemSpectra: PropTypes.bool,
toggleSpectraModal: PropTypes.func.isRequired,
confirmRegenerate: PropTypes.func.isRequired,
};
SpectraEditorBtn.defaultProps = {
hasJcamp: false,
spcInfo: false,
element: {},
hasChemSpectra: false,
};
export default class ReactionDetailsContainers extends Component {
constructor(props) {
super();
const { reaction } = props;
this.state = {
reaction,
activeContainer: 0
};
this.handleChange = this.handleChange.bind(this);
this.handleAdd = this.handleAdd.bind(this);
this.handleRemove = this.handleRemove.bind(this);
this.handleUndo = this.handleUndo.bind(this);
this.handleOnClickRemove = this.handleOnClickRemove.bind(this);
this.handleAccordionOpen = this.handleAccordionOpen.bind(this);
this.handleSpChange = this.handleSpChange.bind(this);
}
componentDidMount() {
TextTemplateActions.fetchTextTemplates('reaction');
}
// eslint-disable-next-line camelcase
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState({
reaction: nextProps.reaction,
});
}
handleChange(container) {
const { reaction } = this.state;
this.props.parent.handleReactionChange(reaction);
}
handleSpChange(reaction, cb) {
this.props.parent.handleReactionChange(reaction);
cb();
}
handleUndo(container) {
const { reaction } = this.state;
container.is_deleted = false;
this.props.parent.handleReactionChange(reaction, { schemaChanged: false });
}
handleAdd() {
const { reaction } = this.state;
const container = Container.buildEmpty();
container.container_type = 'analysis';
container.extended_metadata.content = { ops: [{ insert: '' }] };
if (reaction.container.children.length === 0) {
const analyses = Container.buildEmpty();
analyses.container_type = 'analyses';
reaction.container.children.push(analyses);
}
reaction.container.children.filter(element => (
~element.container_type.indexOf('analyses')
))[0].children.push(container);
const newKey = reaction.container.children.filter(element => (
~element.container_type.indexOf('analyses')
))[0].children.length - 1;
this.handleAccordionOpen(newKey);
this.props.parent.handleReactionChange(reaction, { schemaChanged: false });
}
handleOnClickRemove(container) {
if (confirm('Delete the container?')) {
this.handleRemove(container);
}
}
headerBtnGroup(container, reaction, readOnly) {
const jcampIds = JcampIds(container);
const hasJcamp = jcampIds.orig.length > 0;
const confirmRegenerate = (e) => {
e.stopPropagation();
if (confirm('Regenerate spectra?')) {
LoadingActions.start();
SpectraActions.Regenerate(jcampIds, this.handleChange);
}
};
const spcInfo = BuildSpcInfos(reaction, container);
const { hasChemSpectra } = UIStore.getState();
const toggleSpectraModal = (e) => {
e.stopPropagation();
SpectraActions.ToggleModal();
SpectraActions.LoadSpectra.defer(spcInfo);
};
return (
<div className="upper-btn">
<Button
bsSize="xsmall"
bsStyle="danger"
className="button-right"
disabled={readOnly}
onClick={() => this.handleOnClickRemove(container)}
>
<i className="fa fa-trash" />
</Button>
<PrintCodeButton element={reaction} analyses={[container]} ident={container.id} />
<SpectraEditorBtn
element={reaction}
hasJcamp={hasJcamp}
spcInfo={spcInfo}
hasChemSpectra={hasChemSpectra}
toggleSpectraModal={toggleSpectraModal}
confirmRegenerate={confirmRegenerate}
/>
</div>
);
};
handleRemove(container) {
const { reaction } = this.state;
container.is_deleted = true;
this.props.parent.handleReactionChange(reaction, { schemaChanged: false });
}
handleAccordionOpen(key) {
this.setState({ activeContainer: key });
}
addButton() {
const { readOnly } = this.props;
if (!readOnly) {
return (
<Button
className="button-right"
bsSize="xsmall"
bsStyle="success"
onClick={this.handleAdd}
>
Add analysis
</Button>
);
}
return (<span />);
}
render() {
const { reaction, activeContainer } = this.state;
const { readOnly } = this.props;
const containerHeader = (container) => {
let kind = container.extended_metadata.kind || '';
kind = (kind.split('|')[1] || kind).trim();
const insText = instrumentText(container);
const previewImg = previewContainerImage(container);
const status = container.extended_metadata.status || '';
const content = container.extended_metadata.content || { ops: [{ insert: '' }] };
const contentOneLine = {
ops: content.ops.map((x) => {
const c = Object.assign({}, x);
if (c.insert) c.insert = c.insert.replace(/\n/g, ' ');
return c;
}),
};
let hasPop = true;
let fetchNeeded = false;
let fetchId = 0;
if (previewImg.startsWith('data:image')) {
fetchNeeded = true;
fetchId = container.preview_img.id;
} else {
hasPop = false;
}
return (
<div className="analysis-header order" style={{ width: '100%' }}>
<div className="preview">
<ImageModal
hasPop={hasPop}
previewObject={{
src: previewImg
}}
popObject={{
title: container.name,
src: previewImg,
fetchNeeded,
fetchId
}}
/>
</div>
<div className="abstract">
{
this.headerBtnGroup(container, reaction, readOnly)
}
<div className="lower-text">
<div className="main-title">{container.name}</div>
<div className="sub-title">Type: {kind}</div>
<div className="sub-title">Status: {status} {nmrMsg(reaction, container)} {insText}</div>
<div className="desc sub-title">
<span style={{ float: 'left', marginRight: '5px' }}>
Content:
</span>
<QuillViewer value={contentOneLine} />
</div>
</div>
</div>
</div>
)
};
const containerHeaderDeleted = (container) => {
const kind = container.extended_metadata.kind && container.extended_metadata.kind !== '';
const titleKind = kind ? (` - Type: ${(container.extended_metadata.kind.split('|')[1] || container.extended_metadata.kind).trim()}`) : '';
const status = container.extended_metadata.status && container.extended_metadata.status != '';
const titleStatus = status ? (' - Status: ' + container.extended_metadata.status) : '';
return (
<div style={{ width: '100%' }}>
<strike>
{container.name}
{titleKind}
{titleStatus}
</strike>
<Button className="pull-right" bsSize="xsmall" bsStyle="danger"
onClick={() => this.handleUndo(container)}>
<i className="fa fa-undo"></i>
</Button>
</div>
)
};
if (reaction.container != null && reaction.container.children) {
const analyses_container = reaction.container.children.filter(element => (
~element.container_type.indexOf('analyses')
));
if (analyses_container.length === 1 && analyses_container[0].children.length > 0) {
return (
<div>
<div style={{ marginBottom: '10px' }}>
{this.addButton()}
</div>
<PanelGroup id="reaction-analyses-panel" defaultActiveKey={0} activeKey={activeContainer} onSelect={this.handleAccordionOpen} accordion>
{analyses_container[0].children.map((container, key) => {
if (container.is_deleted) {
return (
<Panel
eventKey={key}
key={`reaction_container_deleted_${container.id}`}
>
<Panel.Heading>{containerHeaderDeleted(container)}</Panel.Heading>
</Panel>
);
}
return (
<Panel
eventKey={key}
key={`reaction_container_${container.id}`}
>
<Panel.Heading>
<Panel.Title toggle>
{containerHeader(container)}
</Panel.Title>
</Panel.Heading>
<Panel.Body collapsible="true">
<ContainerComponent
disabled={readOnly}
readOnly={readOnly}
templateType="reaction"
container={container}
onChange={this.handleChange.bind(this, container)}
/>
<ViewSpectra
sample={reaction}
handleSampleChanged={this.handleSpChange}
handleSubmit={this.props.handleSubmit}
/>
</Panel.Body>
</Panel>
);
})}
</PanelGroup>
</div>
);
}
return (
<div
style={{ marginBottom: '10px' }}
className="noAnalyses-warning"
>
There are currently no Analyses.
{this.addButton()}
</div>
);
}
return (
<div className="noAnalyses-warning">
There are currently no Analyses.
</div>
);
}
}
ReactionDetailsContainers.propTypes = {
readOnly: PropTypes.bool,
parent: PropTypes.object,
handleSubmit: PropTypes.func
};
|
ajax/libs/inferno/1.0.4/inferno-mobx.js | froala/cdnjs | /*!
* inferno-mobx v1.0.4
* (c) 2017 Ryan Megidov
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component'), require('mobx'), require('./inferno-create-class'), require('./inferno-create-element')) :
typeof define === 'function' && define.amd ? define(['inferno-component', 'mobx', 'inferno-create-class', 'inferno-create-element'], factory) :
(global.Inferno = global.Inferno || {}, global.Inferno.Mobx = factory(global.Inferno.Component,global.mobx,global.Inferno.createClass,global.Inferno.createElement));
}(this, (function (Component,mobx,createClass,createElement) { 'use strict';
Component = 'default' in Component ? Component['default'] : Component;
createClass = 'default' in createClass ? createClass['default'] : createClass;
createElement = 'default' in createElement ? createElement['default'] : createElement;
var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.';
// this is MUCH faster than .constructor === Array and instanceof Array
// in Node 7 and the later versions of V8, slower in older versions though
function throwError(message) {
if (!message) {
message = ERROR_MSG;
}
throw new Error(("Inferno Error: " + message));
}
function warning(condition, message) {
if (!condition) {
console.error(message);
}
}
var specialKeys = {
children: true,
key: true,
ref: true
};
var Provider = (function (Component$$1) {
function Provider(props, context) {
Component$$1.call(this, props, context);
this.contextTypes = { mobxStores: function mobxStores() { } };
this.childContextTypes = { mobxStores: function mobxStores() { } };
this.store = props.store;
}
if ( Component$$1 ) Provider.__proto__ = Component$$1;
Provider.prototype = Object.create( Component$$1 && Component$$1.prototype );
Provider.prototype.constructor = Provider;
Provider.prototype.render = function render () {
return this.props.children;
};
Provider.prototype.getChildContext = function getChildContext () {
var this$1 = this;
var stores = {};
// inherit stores
var baseStores = this.context.mobxStores;
if (baseStores) {
for (var key in baseStores) {
stores[key] = baseStores[key];
}
}
// add own stores
for (var key$1 in this$1.props) {
if (!specialKeys[key$1]) {
stores[key$1] = this$1.props[key$1];
}
}
return {
mobxStores: stores
};
};
return Provider;
}(Component));
{
Provider.prototype.componentWillReceiveProps = function (nextProps) {
var this$1 = this;
// Maybe this warning is to aggressive?
warning(Object.keys(nextProps).length === Object.keys(this.props).length, 'MobX Provider: The set of provided stores has changed. ' +
'Please avoid changing stores as the change might not propagate to all children');
for (var key in nextProps) {
warning(specialKeys[key] || this$1.props[key] === nextProps[key], "MobX Provider: Provided store '" + key + "' has changed. " +
"Please avoid replacing stores as the change might not propagate to all children");
}
};
}
var EventEmitter = function EventEmitter() {
this.listeners = [];
};
EventEmitter.prototype.on = function on (cb) {
var this$1 = this;
this.listeners.push(cb);
return function () {
var index = this$1.listeners.indexOf(cb);
if (index !== -1) {
this$1.listeners.splice(index, 1);
}
};
};
EventEmitter.prototype.emit = function emit (data) {
this.listeners.forEach(function (fn) { return fn(data); });
};
EventEmitter.prototype.getTotalListeners = function getTotalListeners () {
return this.listeners.length;
};
EventEmitter.prototype.clearListeners = function clearListeners () {
this.listeners = [];
};
/**
* Dev tools support
*/
var isDevtoolsEnabled = false;
var componentByNodeRegistery = new WeakMap();
var renderReporter = new EventEmitter();
function reportRendering(component) {
var node = component._vNode.dom;
if (node && componentByNodeRegistery) {
componentByNodeRegistery.set(node, component);
}
renderReporter.emit({
event: 'render',
renderTime: component.__$mobRenderEnd - component.__$mobRenderStart,
totalTime: Date.now() - component.__$mobRenderStart,
component: component,
node: node
});
}
function trackComponents() {
if (typeof WeakMap === 'undefined') {
throwError('[inferno-mobx] tracking components is not supported in this browser.');
}
if (!isDevtoolsEnabled) {
isDevtoolsEnabled = true;
}
}
function makeReactive(componentClass) {
var target = componentClass.prototype || componentClass;
var baseDidMount = target.componentDidMount;
var baseWillMount = target.componentWillMount;
var baseUnmount = target.componentWillUnmount;
target.componentWillMount = function () {
var this$1 = this;
// Call original
baseWillMount && baseWillMount.call(this);
var reaction;
var isRenderingPending = false;
var initialName = this.displayName || this.name || (this.constructor && (this.constructor.displayName || this.constructor.name)) || '<component>';
var baseRender = this.render.bind(this);
var initialRender = function (nextProps, nextContext) {
reaction = new mobx.Reaction((initialName + ".render()"), function () {
if (!isRenderingPending) {
isRenderingPending = true;
if (this$1.__$mobxIsUnmounted !== true) {
var hasError = true;
try {
Component.prototype.forceUpdate.call(this$1);
hasError = false;
}
finally {
if (hasError) {
reaction.dispose();
}
}
}
}
});
reactiveRender.$mobx = reaction;
this$1.render = reactiveRender;
return reactiveRender(nextProps, nextContext);
};
var reactiveRender = function (nextProps, nextContext) {
isRenderingPending = false;
var rendering = undefined;
reaction.track(function () {
if (isDevtoolsEnabled) {
this$1.__$mobRenderStart = Date.now();
}
rendering = mobx.extras.allowStateChanges(false, baseRender.bind(this$1, nextProps, nextContext));
if (isDevtoolsEnabled) {
this$1.__$mobRenderEnd = Date.now();
}
});
return rendering;
};
this.render = initialRender;
};
target.componentDidMount = function () {
isDevtoolsEnabled && reportRendering(this);
// Call original
baseDidMount && baseDidMount.call(this);
};
target.componentWillUnmount = function () {
// Call original
baseUnmount && baseUnmount.call(this);
// Dispose observables
this.render.$mobx && this.render.$mobx.dispose();
this.__$mobxIsUnmounted = true;
if (isDevtoolsEnabled) {
var node = this._vNode.dom;
if (node && componentByNodeRegistery) {
componentByNodeRegistery.delete(node);
}
renderReporter.emit({
event: 'destroy',
component: this,
node: node
});
}
};
target.shouldComponentUpdate = function (nextProps, nextState) {
var this$1 = this;
// Update on any state changes (as is the default)
if (this.state !== nextState) {
return true;
}
// Update if props are shallowly not equal, inspired by PureRenderMixin
var keys = Object.keys(this.props);
if (keys.length !== Object.keys(nextProps).length) {
return true;
}
for (var i = keys.length - 1; i >= 0; i--) {
var key = keys[i];
var newValue = nextProps[key];
if (newValue !== this$1.props[key]) {
return true;
}
else if (newValue && typeof newValue === 'object' && !mobx.isObservable(newValue)) {
// If the newValue is still the same object, but that object is not observable,
// fallback to the default behavior: update, because the object *might* have changed.
return true;
}
}
return true;
};
return componentClass;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var index$1 = createCommonjsModule(function (module) {
'use strict';
var INFERNO_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
arguments: true,
arity: true
};
var isGetOwnPropertySymbolsAvailable = typeof Object.getOwnPropertySymbols === 'function';
function hoistNonReactStatics(targetComponent, sourceComponent, customStatics) {
if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components
var keys = Object.getOwnPropertyNames(sourceComponent);
/* istanbul ignore else */
if (isGetOwnPropertySymbolsAvailable) {
keys = keys.concat(Object.getOwnPropertySymbols(sourceComponent));
}
for (var i = 0; i < keys.length; ++i) {
if (!INFERNO_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]] && (!customStatics || !customStatics[keys[i]])) {
try {
targetComponent[keys[i]] = sourceComponent[keys[i]];
} catch (error) {
}
}
}
}
return targetComponent;
}
module.exports = hoistNonReactStatics;
module.exports.default = module.exports;
});
/**
* Store Injection
*/
function createStoreInjector(grabStoresFn, component) {
var Injector = createClass({
displayName: component.name,
render: function render() {
var this$1 = this;
var newProps = {};
for (var key in this$1.props) {
if (this$1.props.hasOwnProperty(key)) {
newProps[key] = this$1.props[key];
}
}
var additionalProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context) || {};
for (var key$1 in additionalProps) {
newProps[key$1] = additionalProps[key$1];
}
newProps.ref = function (instance) {
this$1.wrappedInstance = instance;
};
return createElement(component, newProps);
}
});
Injector.contextTypes = { mobxStores: function mobxStores() { } };
index$1(Injector, component);
return Injector;
}
var grabStoresByName = function (storeNames) {
return function (baseStores, nextProps) {
storeNames.forEach(function (storeName) {
// Prefer props over stores
if (storeName in nextProps) {
return;
}
if (!(storeName in baseStores)) {
throw new Error("MobX observer: Store \"" + storeName + "\" is not available! " +
"Make sure it is provided by some Provider");
}
nextProps[storeName] = baseStores[storeName];
});
return nextProps;
};
};
/**
* Higher order component that injects stores to a child.
* takes either a varargs list of strings, which are stores read from the context,
* or a function that manually maps the available stores from the context to props:
* storesToProps(mobxStores, props, context) => newProps
*/
function inject(grabStoresFn) {
var arguments$1 = arguments;
if (typeof grabStoresFn !== 'function') {
var storesNames = [];
for (var i = 0; i < arguments.length; i++) {
storesNames[i] = arguments$1[i];
}
grabStoresFn = grabStoresByName(storesNames);
}
return function (componentClass) { return createStoreInjector(grabStoresFn, componentClass); };
}
/**
* Wraps a component and provides stores as props
*/
function connect(arg1, arg2) {
if ( arg2 === void 0 ) arg2 = null;
if (typeof arg1 === 'string') {
throwError('Store names should be provided as array');
}
if (Array.isArray(arg1)) {
// component needs stores
if (!arg2) {
// invoked as decorator
return function (componentClass) { return connect(arg1, componentClass); };
}
else {
// TODO: deprecate this invocation style
return inject.apply(null, arg1)(connect(arg2));
}
}
var componentClass = arg1;
// Stateless function component:
// If it is function but doesn't seem to be a Inferno class constructor,
// wrap it to a Inferno class automatically
if (typeof componentClass === 'function'
&& (!componentClass.prototype || !componentClass.prototype.render)
&& !componentClass.isReactClass
&& !Component.isPrototypeOf(componentClass)) {
var newClass = createClass({
displayName: componentClass.displayName || componentClass.name,
propTypes: componentClass.propTypes,
contextTypes: componentClass.contextTypes,
getDefaultProps: function () { return componentClass.defaultProps; },
render: function render() {
return componentClass.call(this, this.props, this.context);
}
});
return connect(newClass);
}
if (!componentClass) {
throwError('Please pass a valid component to "observer"');
}
componentClass.isMobXReactObserver = true;
return makeReactive(componentClass);
}
var index = {
Provider: Provider,
inject: inject,
connect: connect,
observer: connect,
trackComponents: trackComponents,
renderReporter: renderReporter,
componentByNodeRegistery: componentByNodeRegistery
};
return index;
})));
|
src/svg-icons/action/system-update-alt.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSystemUpdateAlt = (props) => (
<SvgIcon {...props}>
<path d="M12 16.5l4-4h-3v-9h-2v9H8l4 4zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
ActionSystemUpdateAlt = pure(ActionSystemUpdateAlt);
ActionSystemUpdateAlt.displayName = 'ActionSystemUpdateAlt';
ActionSystemUpdateAlt.muiName = 'SvgIcon';
export default ActionSystemUpdateAlt;
|
app/javascript/mastodon/components/admin/Dimension.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import api from 'mastodon/api';
import { FormattedNumber } from 'react-intl';
import { roundTo10 } from 'mastodon/utils/numbers';
import Skeleton from 'mastodon/components/skeleton';
export default class Dimension extends React.PureComponent {
static propTypes = {
dimension: PropTypes.string.isRequired,
start_at: PropTypes.string.isRequired,
end_at: PropTypes.string.isRequired,
limit: PropTypes.number.isRequired,
label: PropTypes.string.isRequired,
params: PropTypes.object,
};
state = {
loading: true,
data: null,
};
componentDidMount () {
const { start_at, end_at, dimension, limit, params } = this.props;
api().post('/api/v1/admin/dimensions', { keys: [dimension], start_at, end_at, limit, [dimension]: params }).then(res => {
this.setState({
loading: false,
data: res.data,
});
}).catch(err => {
console.error(err);
});
}
render () {
const { label, limit } = this.props;
const { loading, data } = this.state;
let content;
if (loading) {
content = (
<table>
<tbody>
{Array.from(Array(limit)).map((_, i) => (
<tr className='dimension__item' key={i}>
<td className='dimension__item__key'>
<Skeleton width={100} />
</td>
<td className='dimension__item__value'>
<Skeleton width={60} />
</td>
</tr>
))}
</tbody>
</table>
);
} else {
const sum = data[0].data.reduce((sum, cur) => sum + (cur.value * 1), 0);
content = (
<table>
<tbody>
{data[0].data.map(item => (
<tr className='dimension__item' key={item.key}>
<td className='dimension__item__key'>
<span className={`dimension__item__indicator dimension__item__indicator--${roundTo10(((item.value * 1) / sum) * 100)}`} />
<span title={item.key}>{item.human_key}</span>
</td>
<td className='dimension__item__value'>
{typeof item.human_value !== 'undefined' ? item.human_value : <FormattedNumber value={item.value} />}
</td>
</tr>
))}
</tbody>
</table>
);
}
return (
<div className='dimension'>
<h4>{label}</h4>
{content}
</div>
);
}
}
|
test/fixtures/mjs-support/src/index.js | mangomint/create-react-app | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
|
moban1117/js/jquery-1.11.0.min.js | wangyunzhong123/mywebproject | /*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f
}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
},a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
|
ajax/libs/falcor/0.0.16/falcor.browser.js | joeyparrish/cdnjs | /*!
* Copyright 2014 Netflix, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
(function e(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var falcor = require('./index');
var HttpDataSource = require('falcor-browser');
falcor.HttpDataSource = HttpDataSource;
module.exports = falcor;
},{"./index":2,"falcor-browser":149}],2:[function(require,module,exports){
var falcor = require('./lib/falcor');
var get = require('./lib/get');
var set = require('./lib/set');
var inv = require('./lib/invalidate');
var prototype = falcor.Model.prototype;
prototype._getBoundValue = get.getBoundValue;
prototype._getValueSync = get.getValueSync;
prototype._getPathSetsAsValues = get.getAsValues;
prototype._getPathSetsAsJSON = get.getAsJSON;
prototype._getPathSetsAsPathMap = get.getAsPathMap;
prototype._getPathSetsAsJSONG = get.getAsJSONG;
prototype._getPathMapsAsValues = get.getAsValues;
prototype._getPathMapsAsJSON = get.getAsJSON;
prototype._getPathMapsAsPathMap = get.getAsPathMap;
prototype._getPathMapsAsJSONG = get.getAsJSONG;
prototype._setPathSetsAsJSON = set.setPathSetsAsJSON;
prototype._setPathSetsAsJSONG = set.setPathSetsAsJSONG;
prototype._setPathSetsAsPathMap = set.setPathSetsAsPathMap;
prototype._setPathSetsAsValues = set.setPathSetsAsValues;
prototype._setPathMapsAsJSON = set.setPathMapsAsJSON;
prototype._setPathMapsAsJSONG = set.setPathMapsAsJSONG;
prototype._setPathMapsAsPathMap = set.setPathMapsAsPathMap;
prototype._setPathMapsAsValues = set.setPathMapsAsValues;
prototype._setJSONGsAsJSON = set.setJSONGsAsJSON;
prototype._setJSONGsAsJSONG = set.setJSONGsAsJSONG;
prototype._setJSONGsAsPathMap = set.setJSONGsAsPathMap;
prototype._setJSONGsAsValues = set.setJSONGsAsValues;
prototype._invPathSetsAsJSON = inv.invPathSetsAsJSON;
prototype._invPathSetsAsJSONG = inv.invPathSetsAsJSONG;
prototype._invPathSetsAsPathMap = inv.invPathSetsAsPathMap;
prototype._invPathSetsAsValues = inv.invPathSetsAsValues;
// prototype._setCache = get.setCache;
prototype._setCache = set.setCache;
module.exports = falcor;
},{"./lib/falcor":6,"./lib/get":48,"./lib/invalidate":77,"./lib/set":85}],3:[function(require,module,exports){
if (typeof falcor === 'undefined') {
var falcor = {};
}
var Rx = require('rx');
falcor.__Internals = {};
falcor.Observable = Rx.Observable;
falcor.EXPIRES_NOW = 0;
falcor.EXPIRES_NEVER = 1;
/**
* The current semVer'd data version of falcor.
*/
falcor.dataVersion = '0.1.0';
falcor.now = function now() {
return Date.now();
};
falcor.NOOP = function() {};
module.exports = falcor;
},{"rx":168}],4:[function(require,module,exports){
var falcor = require('./Falcor');
var RequestQueue = require('./request/RequestQueue');
var ImmediateScheduler = require('./scheduler/ImmediateScheduler');
var TimeoutScheduler = require('./scheduler/TimeoutScheduler');
var ERROR = require("../types/error");
var ModelResponse = require('./ModelResponse');
var call = require('./operations/call');
var operations = require('./operations');
var pathSyntax = require('falcor-path-syntax');
var getBoundValue = require('./../get/getBoundValue');
var slice = Array.prototype.slice;
var $ref = require('./../types/path');
var $error = require('./../types/error');
var $sentinel = require('./../types/sentinel');
var Model = module.exports = falcor.Model = function Model(options) {
if (!options) {
options = {};
}
this._materialized = options.materialized || false;
this._boxed = options.boxed || false;
this._treatErrorsAsValues = options.treatErrorsAsValues || false;
this._dataSource = options.source;
this._maxSize = options.maxSize || Math.pow(2, 53) - 1;
this._collectRatio = options.collectRatio || 0.75;
this._scheduler = new ImmediateScheduler();
this._request = new RequestQueue(this, this._scheduler);
this._errorSelector = options.errorSelector || Model.prototype._errorSelector;
this._router = options.router;
this._root = options.root || {
expired: [],
allowSync: 0,
unsafeMode: false
};
if (options.cache && typeof options.cache === "object") {
this.setCache(options.cache);
} else {
this._cache = {};
}
this._path = [];
};
Model.EXPIRES_NOW = falcor.EXPIRES_NOW;
Model.EXPIRES_NEVER = falcor.EXPIRES_NEVER;
Model.ref = function(path) {
if (typeof path === 'string') {
path = pathSyntax(path);
}
return {$type: $ref, value: path};
};
Model.error = function(error) {
return {$type: $error, value: error};
};
Model.atom = function(value) {
return {$type: $sentinel, value: value};
};
Model.prototype = {
_boxed: false,
_progressive: false,
_errorSelector: function(x, y) { return y; },
get: operations("get"),
set: operations("set"),
invalidate: operations("invalidate"),
call: call,
getValue: function(path) {
return this.get(path, function(x) { return x; });
},
setValue: function(path, value) {
path = pathSyntax.fromPath(path);
return this.set(Array.isArray(path) ?
{path: path, value: value} :
path, function(x) { return x; });
},
bind: function(boundPath) {
var model = this, root = model._root,
paths = new Array(arguments.length - 1),
i = -1, n = arguments.length - 1;
boundPath = pathSyntax.fromPath(boundPath);
while(++i < n) {
paths[i] = pathSyntax.fromPath(arguments[i + 1]);
}
if(n === 0) { throw new Error("Model#bind requires at least one value path."); }
return falcor.Observable.create(function(observer) {
var boundModel;
root.allowSync++;
try {
boundModel = model.bindSync(model._path.concat(boundPath));
if (!boundModel) {
throw false;
}
observer.onNext(boundModel);
observer.onCompleted();
} catch (e) {
return model.get.apply(model, paths.map(function(path) {
return boundPath.concat(path);
}).concat(function(){})).subscribe(
function onNext() {},
function onError(err) { observer.onError(err); },
function onCompleted() {
root.allowSync++;
try {
boundModel = model.bindSync(boundPath);
if(boundModel) {
observer.onNext(boundModel);
}
observer.onCompleted();
} catch(e) {
observer.onError(e);
}
// remove the inc
finally {
root.allowSync--;
}
});
}
// remove the inc
finally {
root.allowSync--;
}
});
},
setCache: function(cache) {
return (this._cache = {}) && this._setCache(this, cache);
},
getCache: function() {
var pathmaps = [{}];
var tmpCache = this.boxValues().treatErrorsAsValues().materialize();
tmpCache._getPathMapsAsPathMap(tmpCache, [tmpCache._cache], pathmaps);
return pathmaps[0].json;
},
getValueSync: function(path) {
path = pathSyntax.fromPath(path);
if (Array.isArray(path) === false) {
throw new Error("Model#getValueSync must be called with an Array path.");
}
if (this._path.length) {
path = this._path.concat(path);
}
return this.syncCheck("getValueSync") && this._getValueSync(this, path).value;
},
setValueSync: function(path, value, errorSelector) {
path = pathSyntax.fromPath(path);
if(Array.isArray(path) === false) {
if(typeof errorSelector !== "function") {
errorSelector = value || this._errorSelector;
}
value = path.value;
path = path.path;
}
if(Array.isArray(path) === false) {
throw new Error("Model#setValueSync must be called with an Array path.");
}
if(this.syncCheck("setValueSync")) {
var json = {};
var tEeAV = this._treatErrorsAsValues;
var boxed = this._boxed;
this._treatErrorsAsValues = true;
this._boxed = true;
this._setPathSetsAsJSON(this, [{path: path, value: value}], [json], errorSelector);
this._treatErrorsAsValues = tEeAV;
this._boxed = boxed;
json = json.json;
if(json && json.$type === ERROR && !this._treatErrorsAsValues) {
if(this._boxed) {
throw json;
} else {
throw json.value;
}
} else if(this._boxed) {
return json;
}
return json && json.value;
}
},
bindSync: function(path) {
path = pathSyntax.fromPath(path);
if(Array.isArray(path) === false) {
throw new Error("Model#bindSync must be called with an Array path.");
}
var boundValue = this.syncCheck("bindSync") && getBoundValue(this, this._path.concat(path));
var node = boundValue.value;
path = boundValue.path;
if(boundValue.shorted) {
if(!!node) {
if(node.$type === ERROR) {
if(this._boxed) {
throw node;
}
throw node.value;
// throw new Error("Model#bindSync can\'t bind to or beyond an error: " + boundValue.toString());
}
}
return undefined;
} else if(!!node && node.$type === ERROR) {
if(this._boxed) {
throw node;
}
throw node.value;
}
return this.clone(["_path", boundValue.path]);
},
clone: function() {
var self = this;
var clone = new Model();
var key, keyValue;
var keys = Object.keys(self);
var keysIdx = -1;
var keysLen = keys.length;
while(++keysIdx < keysLen) {
key = keys[keysIdx];
clone[key] = self[key];
}
var argsIdx = -1;
var argsLen = arguments.length;
while(++argsIdx < argsLen) {
keyValue = arguments[argsIdx];
clone[keyValue[0]] = keyValue[1];
}
return clone;
},
batch: function(schedulerOrDelay) {
if(typeof schedulerOrDelay === "number") {
schedulerOrDelay = new TimeoutScheduler(Math.round(Math.abs(schedulerOrDelay)));
} else if(!schedulerOrDelay || !schedulerOrDelay.schedule) {
schedulerOrDelay = new ImmediateScheduler();
}
return this.clone(["_request", new RequestQueue(this, schedulerOrDelay)]);
},
unbatch: function() {
return this.clone(["_request", new RequestQueue(this, new ImmediateScheduler())]);
},
treatErrorsAsValues: function() {
return this.clone(["_treatErrorsAsValues", true]);
},
materialize: function() {
return this.clone(["_materialized", true]);
},
boxValues: function() {
return this.clone(["_boxed", true]);
},
unboxValues: function() {
return this.clone(["_boxed", false]);
},
withoutDataSource: function() {
return this.clone(["_dataSource", null]);
},
syncCheck: function(name) {
if (!!this._dataSource && this._root.allowSync <= 0 && this._root.unsafeMode === false) {
throw new Error("Model#" + name + " may only be called within the context of a request selector.");
}
return true;
}
};
},{"../types/error":135,"./../get/getBoundValue":45,"./../types/error":135,"./../types/path":136,"./../types/sentinel":137,"./Falcor":3,"./ModelResponse":5,"./operations":12,"./operations/call":7,"./request/RequestQueue":37,"./scheduler/ImmediateScheduler":38,"./scheduler/TimeoutScheduler":39,"falcor-path-syntax":152}],5:[function(require,module,exports){
var falcor = require('./Falcor');
var pathSyntax = require('falcor-path-syntax');
if(typeof Promise !== "undefined" && Promise) {
falcor.Promise = Promise;
} else {
falcor.Promise = require("promise");
}
var Observable = falcor.Observable,
valuesMixin = { format: { value: "AsValues" } },
jsonMixin = { format: { value: "AsPathMap" } },
jsongMixin = { format: { value: "AsJSONG" } },
progressiveMixin = { operationIsProgressive: { value: true } };
function ModelResponse(forEach) {
this._subscribe = forEach;
}
ModelResponse.create = function(forEach) {
return new ModelResponse(forEach);
};
ModelResponse.fromOperation = function(model, args, selector, forEach) {
return new ModelResponse(function(observer) {
return forEach(Object.create(observer, {
operationModel: {value: model},
operationArgs: {value: pathSyntax.fromPathsOrPathValues(args)},
operationSelector: {value: selector}
}));
});
};
function noop() {}
function mixin(self) {
var mixins = Array.prototype.slice.call(arguments, 1);
return new ModelResponse(function(other) {
return self.subscribe(mixins.reduce(function(proto, mixin) {
return Object.create(proto, mixin);
}, other));
});
}
ModelResponse.prototype = Observable.create(noop);
ModelResponse.prototype.format = "AsPathMap";
ModelResponse.prototype.toPathValues = function() {
return mixin(this, valuesMixin);
};
ModelResponse.prototype.toJSON = function() {
return mixin(this, jsonMixin);
};
ModelResponse.prototype.progressively = function() {
return mixin(this, progressiveMixin);
};
ModelResponse.prototype.toJSONG = function() {
return mixin(this, jsongMixin);
};
ModelResponse.prototype.then = function(onNext, onError) {
var self = this;
return new falcor.Promise(function(resolve, reject) {
setTimeout(function() {
var value = undefined;
var error = undefined;
self.toArray().subscribe(
function(values) {
if(values.length <= 1) {
value = values[0];
} else {
value = values;
}
},
function(errors) {
if(errors.length <= 1) {
error = errors[0];
} else {
error = errors;
}
resolve = undefined;
},
function() {
if(!!resolve) {
resolve(value);
} else {
reject(error);
}
}
);
}, 0);
}).then(onNext, onError);
};
module.exports = ModelResponse;
},{"./Falcor":3,"falcor-path-syntax":152,"promise":158}],6:[function(require,module,exports){
var falcor = require('./Falcor');
var Model = require('./Model');
falcor.Model = Model;
module.exports = falcor;
},{"./Falcor":3,"./Model":4}],7:[function(require,module,exports){
module.exports = call;
var falcor = require("../../Falcor");
var ModelResponse = require('./../../ModelResponse');
function call(path, args, suffixes, paths, selector) {
var model = this;
args && Array.isArray(args) || (args = []);
suffixes && Array.isArray(suffixes) || (suffixes = []);
paths = Array.prototype.slice.call(arguments, 3);
if (typeof (selector = paths[paths.length - 1]) !== "function") {
selector = undefined;
} else {
paths = paths.slice(0, -1);
}
return ModelResponse.create(function (options) {
var rootModel = model.clone(["_path", []]),
localRoot = rootModel.withoutDataSource(),
dataSource = model._dataSource,
boundPath = model._path,
callPath = boundPath.concat(path),
thisPath = callPath.slice(0, -1);
var disposable = model.
getValue(path).
flatMap(function (localFn) {
if (typeof localFn === "function") {
return falcor.Observable.return(localFn.
apply(rootModel.bindSync(thisPath), args).
map(function (pathValue) {
return {
path: thisPath.concat(pathValue.path),
value: pathValue.value
};
}).
toArray().
flatMap(function (pathValues) {
return localRoot.set.
apply(localRoot, pathValues).
toJSONG();
}).
flatMap(function (envelope) {
return rootModel.get.apply(rootModel,
envelope.paths.reduce(function (paths, path) {
return paths.concat(suffixes.map(function (suffix) {
return path.concat(suffix);
}));
}, []).
concat(paths.reduce(function (paths, path) {
return paths.concat(thisPath.concat(path));
}, []))).
toJSONG();
}));
}
return falcor.Observable.empty();
}).
defaultIfEmpty(dataSource.call(path, args, suffixes, paths)).
mergeAll().
subscribe(function (envelope) {
var invalidated = envelope.invalidated;
if (invalidated && invalidated.length) {
invalidatePaths(rootModel, invalidated, undefined, model._errorSelector);
}
disposable = localRoot.
set(envelope, function () {
return model;
}).
subscribe(function (model) {
var getPaths = envelope.paths.map(function (path) {
return path.slice(boundPath.length);
});
if (selector) {
getPaths[getPaths.length] = function () {
return selector.call(model, getPaths);
};
}
disposable = model.get.apply(model, getPaths).subscribe(options);
});
});
return {
dispose: function () {
disposable && disposable.dispose();
disposable = undefined;
}
};
});
}
},{"../../Falcor":3,"./../../ModelResponse":5}],8:[function(require,module,exports){
var combineOperations = require('./../support/combineOperations');
var setSeedsOrOnNext = require('./../support/setSeedsOrOnNext');
/**
* The initial args that are passed into the async request pipeline.
* @see lib/falcor/operations/request.js for how initialArgs are used
*/
module.exports = function getInitialArgs(options, seeds, onNext) {
var seedRequired = options.format !== 'AsValues';
var isProgressive = options.operationIsProgressive;
var spreadOperations = false;
var operations =
combineOperations(
options.operationArgs, options.format, 'get',
spreadOperations, isProgressive);
setSeedsOrOnNext(
operations, seedRequired, seeds, onNext, options.operationSelector);
var requestOptions;
return [operations];
};
},{"./../support/combineOperations":23,"./../support/setSeedsOrOnNext":36}],9:[function(require,module,exports){
var getSourceObserver = require('./../support/getSourceObserever');
var partitionOperations = require('./../support/partitionOperations');
var mergeBoundPath = require('./../support/mergeBoundPath');
module.exports = getSourceRequest;
function getSourceRequest(
options, onNext, seeds, combinedResults, requestOptions, cb) {
var model = options.operationModel;
var boundPath = model._path;
var missingPaths = combinedResults.requestedMissingPaths;
if (boundPath.length) {
for (var i = 0; i < missingPaths.length; ++i) {
var pathSetIndex = missingPaths[i].pathSetIndex;
var path = missingPaths[i] = boundPath.concat(missingPaths[i]);
path.pathSetIndex = pathSetIndex;
}
}
return model._request.get(
missingPaths,
combinedResults.optimizedMissingPaths,
getSourceObserver(
model,
missingPaths,
function getSourceCallback(err, results) {
if (err) {
cb(err);
return;
}
// partitions the operations by their pathSetIndex
var partitionOperationsAndSeeds = partitionOperations(
results,
seeds,
options.format,
onNext);
// We allow for the rerequesting to happen.
cb(null, partitionOperationsAndSeeds);
}));
}
},{"./../support/getSourceObserever":24,"./../support/mergeBoundPath":28,"./../support/partitionOperations":31}],10:[function(require,module,exports){
var getInitialArgs = require('./getInitialArgs');
var getSourceRequest = require('./getSourceRequest');
var shouldRequest = require('./shouldRequest');
var request = require('./../request');
var processOperations = require('./../support/processOperations');
var get = request(
getInitialArgs,
getSourceRequest,
processOperations,
shouldRequest);
module.exports = get;
},{"./../request":15,"./../support/processOperations":33,"./getInitialArgs":8,"./getSourceRequest":9,"./shouldRequest":11}],11:[function(require,module,exports){
module.exports = function(model, combinedResults) {
return model._dataSource && combinedResults.requestedMissingPaths.length > 0;
};
},{}],12:[function(require,module,exports){
var ModelResponse = require('../ModelResponse');
var get = require('./get');
var set = require('./set');
var invalidate = require('./invalidate');
module.exports = function modelOperation(name) {
return function() {
var model = this, root = model._root,
args = Array.prototype.slice.call(arguments),
selector = args[args.length - 1];
if (typeof selector === 'function') {
args.pop();
} else {
selector = false;
}
var modelResponder;
switch (name) {
case 'get':
modelResponder = get;
break;
case 'set':
modelResponder = set;
break;
case 'invalidate':
modelResponder = invalidate;
break;
}
return ModelResponse.fromOperation(
model,
args,
selector,
modelResponder);
};
};
},{"../ModelResponse":5,"./get":10,"./invalidate":13,"./set":16}],13:[function(require,module,exports){
var invalidateInitialArgs = require('./invalidateInitialArgs');
var request = require('./../request');
var processOperations = require('./../support/processOperations');
var invalidate = request(
invalidateInitialArgs,
null,
processOperations);
module.exports = invalidate;
},{"./../request":15,"./../support/processOperations":33,"./invalidateInitialArgs":14}],14:[function(require,module,exports){
var combineOperations = require('./../support/combineOperations');
var setSeedsOrOnNext = require('./../support/setSeedsOrOnNext');
module.exports = function getInitialArgs(options, seeds, onNext) {
var seedRequired = options.format !== 'AsValues';
var operations = combineOperations(
options.operationArgs, options.format, 'inv');
setSeedsOrOnNext(
operations, seedRequired, seeds,
onNext, options.operationSelector);
return [operations, seeds];
};
},{"./../support/combineOperations":23,"./../support/setSeedsOrOnNext":36}],15:[function(require,module,exports){
var setSeedsOrOnNext = require('./support/setSeedsOrOnNext');
var onNextValues = require('./support/onNextValue');
var onCompletedOrError = require('./support/onCompletedOrError');
var primeSeeds = require('./support/primeSeeds');
var autoFalse = function() { return false; };
module.exports = request;
function request(initialArgs, sourceRequest, processOperations, shouldRequestFn) {
if (!shouldRequestFn) {
shouldRequestFn = autoFalse;
}
return function innerRequest(options) {
var selector = options.operationSelector;
var model = options.operationModel;
var args = options.operationArgs;
var onNext = options.onNext.bind(options);
var onError = options.onError.bind(options);
var onCompleted = options.onCompleted.bind(options);
var isProgressive = options.operationIsProgressive;
var errorSelector = model._errorSelector;
var selectorLength = selector && selector.length || 0;
// State variables
var errors = [];
var format = options.format = selector && 'AsJSON' ||
options.format || 'AsPathMap';
var toJSONG = format === 'AsJSONG';
var toJSON = format === 'AsPathMap';
var toPathValues = format === 'AsValues';
var seedRequired = toJSON || toJSONG || selector;
var boundPath = model._path;
var i, len;
var foundValue = false;
var seeds = primeSeeds(selector, selectorLength);
var loopCount = 0;
function recurse(operations, opts) {
if (loopCount > 50) {
throw 'Loop Kill switch thrown.';
}
var combinedResults = processOperations(
model,
operations,
errorSelector,
opts);
foundValue = foundValue || combinedResults.valuesReceived;
if (combinedResults.errors.length) {
errors = errors.concat(combinedResults.errors);
}
// if in progressiveMode, values are emitted
// each time through the recurse loop. This may have
// to change when the router is considered.
if (isProgressive && !toPathValues) {
onNextValues(model, onNext, seeds, selector);
}
// Performs the recursing via dataSource
if (shouldRequestFn(model, combinedResults, loopCount)) {
sourceRequest(
options,
onNext,
seeds,
combinedResults,
opts,
function onCompleteFromSourceSet(err, results) {
if (err) {
errors = errors.concat(err);
recurse([], seeds);
return;
}
++loopCount;
// We continue to string the opts through
recurse(results, opts);
});
}
// Else we need to onNext values and complete/error.
else {
if (!toPathValues && !isProgressive && foundValue) {
onNextValues(model, onNext, seeds, selector);
}
onCompletedOrError(onCompleted, onError, errors);
}
}
try {
recurse.apply(null,
initialArgs(options, seeds, onNext));
} catch(e) {
errors = [e];
onCompletedOrError(onCompleted, onError, errors);
}
};
}
},{"./support/onCompletedOrError":29,"./support/onNextValue":30,"./support/primeSeeds":32,"./support/setSeedsOrOnNext":36}],16:[function(require,module,exports){
var setInitialArgs = require('./setInitialArgs');
var setSourceRequest = require('./setSourceRequest');
var request = require('./../request');
var setProcessOperations = require('./setProcessOperations');
var shouldRequest = require('./shouldRequest');
var set = request(
setInitialArgs,
setSourceRequest,
setProcessOperations,
shouldRequest);
module.exports = set;
},{"./../request":15,"./setInitialArgs":17,"./setProcessOperations":18,"./setSourceRequest":19,"./shouldRequest":20}],17:[function(require,module,exports){
var combineOperations = require('./../support/combineOperations');
var setSeedsOrOnNext = require('./../support/setSeedsOrOnNext');
var Formats = require('./../support/Formats');
var toPathValues = Formats.toPathValues;
var toJSONG = Formats.toJSONG;
module.exports = function setInitialArgs(options, seeds, onNext) {
var isPathValues = options.format === toPathValues;
var seedRequired = !isPathValues;
var shouldRequest = !!options.operationModel._dataSource;
var format = options.format;
var args = options.operationArgs;
var selector = options.operationSelector;
var isProgressive = options.operationIsProgressive;
var firstSeeds, operations;
var requestOptions = {
removeBoundPath: shouldRequest
};
// If Model is a slave, in shouldRequest mode,
// a single seed is required to accumulate the jsong results.
if (shouldRequest) {
operations =
combineOperations(args, toJSONG, 'set', selector, false);
firstSeeds = [{}];
setSeedsOrOnNext(
operations, true, firstSeeds, false, options.selector);
// we must keep track of the set seeds.
requestOptions.requestSeed = firstSeeds[0];
}
// This model is the master, therefore a regular set can be performed.
else {
firstSeeds = seeds;
operations = combineOperations(args, format, 'set');
setSeedsOrOnNext(
operations, seedRequired, seeds, onNext, options.operationSelector);
}
// We either have to construct the master operations if
// the ModelResponse is isProgressive
// the ModelResponse is toPathValues
// but luckily we can just perform a get for the progressive or
// toPathValues mode.
if (isProgressive || isPathValues) {
var getOps = combineOperations(
args, format, 'get', selector, true);
setSeedsOrOnNext(
getOps, seedRequired, seeds, onNext, options.operationSelector);
operations = operations.concat(getOps);
requestOptions.isProgressive = true;
}
return [operations, requestOptions];
};
},{"./../support/Formats":21,"./../support/combineOperations":23,"./../support/setSeedsOrOnNext":36}],18:[function(require,module,exports){
var processOperations = require('./../support/processOperations');
var combineOperations = require('./../support/combineOperations');
var mergeBoundPath = require('./../support/mergeBoundPath');
var Formats = require('./../support/Formats');
var toPathValues = Formats.toPathValues;
module.exports = setProcessOperations;
function setProcessOperations(model, operations, errorSelector, requestOptions) {
var boundPath = model._path;
var hasBoundPath = boundPath.length > 0;
var removeBoundPath = requestOptions && requestOptions.removeBoundPath;
var isProgressive = requestOptions && requestOptions.isProgressive;
var progressiveOperations;
// if in progressive mode, then the progressive operations
// need to be executed but the bound path must stay intact.
if (isProgressive && removeBoundPath && hasBoundPath) {
progressiveOperations = operations.filter(function(op) {
return op.isProgressive;
});
operations = operations.filter(function(op) {
return !op.isProgressive;
});
}
if (removeBoundPath && hasBoundPath) {
model._path = [];
// For every operations arguments, the bound path must be adjusted.
for (var i = 0, opLen = operations.length; i < opLen; i++) {
var args = operations[i].args;
for (var j = 0, argsLen = args.length; j < argsLen; j++) {
args[j] = mergeBoundPath(args[j], boundPath);
}
}
}
var results = processOperations(model, operations, errorSelector);
// Undo what we have done to the model's bound path.
if (removeBoundPath && hasBoundPath) {
model._path = boundPath;
}
// executes the progressive ops
if (progressiveOperations) {
processOperations(model, progressiveOperations, errorSelector);
}
return results;
}
},{"./../support/Formats":21,"./../support/combineOperations":23,"./../support/mergeBoundPath":28,"./../support/processOperations":33}],19:[function(require,module,exports){
var getSourceObserver = require('./../support/getSourceObserever');
var combineOperations = require('./../support/combineOperations');
var setSeedsOrOnNext = require('./../support/setSeedsOrOnNext');
var toPathValues = require('./../support/Formats').toPathValues;
module.exports = setSourceRequest;
function setSourceRequest(
options, onNext, seeds, combinedResults, requestOptions, cb) {
var model = options.operationModel;
var seedRequired = options.format !== toPathValues;
var requestSeed = requestOptions.requestSeed;
return model._request.set(
requestSeed,
getSourceObserver(
model,
requestSeed.paths,
function setSourceRequestCB(err, results) {
if (err) {
cb(err);
}
// Sets the results into the model.
model._setJSONGsAsJSON(model, [results], []);
// Gets the original paths / maps back out.
var operations = combineOperations(
options.operationArgs, options.format, 'get');
setSeedsOrOnNext(
operations, seedRequired,
seeds, onNext, options.operationSelector);
// unset the removeBoundPath.
requestOptions.removeBoundPath = false;
cb(null, operations);
}));
}
},{"./../support/Formats":21,"./../support/combineOperations":23,"./../support/getSourceObserever":24,"./../support/setSeedsOrOnNext":36}],20:[function(require,module,exports){
// Set differs from get in the sense that the first time through
// the recurse loop a server operation must be performed if it can be.
module.exports = function(model, combinedResults, loopCount) {
return model._dataSource && (
combinedResults.requestedMissingPaths.length > 0 ||
loopCount === 0);
};
},{}],21:[function(require,module,exports){
module.exports = {
toPathValues: 'AsValues',
toJSON: 'AsPathMap',
toJSONG: 'AsJSONG',
selector: 'AsJSON',
};
},{}],22:[function(require,module,exports){
module.exports = function buildJSONGOperation(format, seeds, jsongOp, seedOffset, onNext) {
return {
methodName: '_setJSONGs' + format,
format: format,
isValues: format === 'AsValues',
onNext: onNext,
seeds: seeds,
seedsOffset: seedOffset,
args: [jsongOp]
};
};
},{}],23:[function(require,module,exports){
var isSeedRequired = require('./seedRequired');
var isJSONG = require('./isJSONG');
var isPathOrPathValue = require('./isPathOrPathValue');
var Formats = require('./Formats');
var toSelector = Formats.selector;
module.exports = function combineOperations(args, format, name, spread, isProgressive) {
var seedRequired = isSeedRequired(format);
var isValues = !seedRequired;
var hasSelector = seedRequired && format === toSelector;
var seedsOffset = 0;
return args.
reduce(function(groups, argument) {
var group = groups[groups.length - 1];
var type = isPathOrPathValue(argument) ? "PathSets" :
isJSONG(argument) ? "JSONGs" : "PathMaps";
var groupType = group && group.type;
var methodName = '_' + name + type + format;
if (!groupType || type !== groupType || spread) {
group = {
methodName: methodName,
format: format,
operation: name,
isValues: isValues,
seeds: [],
onNext: null,
seedsOffset: seedsOffset,
isProgressive: isProgressive,
type: type,
args: []
};
groups.push(group);
}
if (hasSelector) {
++seedsOffset;
}
group.args.push(argument);
return groups;
}, []);
};
},{"./Formats":21,"./isJSONG":26,"./isPathOrPathValue":27,"./seedRequired":34}],24:[function(require,module,exports){
var insertErrors = require('./insertErrors.js');
/**
* creates the model source observer
* @param {Model} model
* @param {Array.<Array>} requestedMissingPaths
* @param {Function} cb
*/
function getSourceObserver(model, requestedMissingPaths, cb) {
var incomingValues;
return {
onNext: function(jsongEnvelop) {
incomingValues = {
jsong: jsongEnvelop.jsong,
paths: requestedMissingPaths
};
},
onError: function(err) {
cb(insertErrors(model, requestedMissingPaths, err));
},
onCompleted: function() {
cb(false, incomingValues);
}
};
}
module.exports = getSourceObserver;
},{"./insertErrors.js":25}],25:[function(require,module,exports){
/**
* will insert the error provided for every requestedPath.
* @param {Model} model
* @param {Array.<Array>} requestedPaths
* @param {Object} err
*/
module.exports = function insertErrors(model, requestedPaths, err) {
var out = model._setPathSetsAsJSON.apply(null, [model].concat(
requestedPaths.
reduce(function(acc, r) {
acc[0].push({
path: r,
value: err
});
return acc;
}, [[]]),
[],
model._errorSelector
));
return out.errors;
};
},{}],26:[function(require,module,exports){
module.exports = function isJSONG(x) {
return x.hasOwnProperty("jsong");
};
},{}],27:[function(require,module,exports){
module.exports = function isPathOrPathValue(x) {
return !!(Array.isArray(x)) || (
x.hasOwnProperty("path") && x.hasOwnProperty("value"));
};
},{}],28:[function(require,module,exports){
var isJSONG = require('./isJSONG');
var isPathValue = require('./isPathOrPathValue');
module.exports = mergeBoundPath;
function mergeBoundPath(arg, boundPath) {
return isJSONG(arg) && mergeBoundPathIntoJSONG(arg, boundPath) ||
isPathValue(arg) && mergeBoundPathIntoPathValue(arg, boundPath) ||
mergeBoundPathIntoJSON(arg, boundPath);
}
function mergeBoundPathIntoJSONG(jsongEnv, boundPath) {
var newJSONGEnv = {jsong: jsongEnv.jsong, paths: jsongEnv.paths};
if (boundPath.length) {
var paths = [];
for (i = 0, len = jsongEnv.paths.length; i < len; i++) {
paths[i] = boundPath.concat(jsongEnv.paths[i]);
}
newJSONGEnv.paths = paths;
}
return newJSONGEnv;
}
function mergeBoundPathIntoJSON(arg, boundPath) {
var newArg = arg;
if (boundPath.length) {
newArg = {};
for (var i = 0, len = boundPath.length - 1; i < len; i++) {
newArg[boundPath[i]] = {};
}
newArg[boundPath[i]] = arg;
}
return newArg;
}
function mergeBoundPathIntoPathValue(arg, boundPath) {
return {
path: boundPath.concat(arg.path),
value: arg.value
};
}
},{"./isJSONG":26,"./isPathOrPathValue":27}],29:[function(require,module,exports){
module.exports = function onCompletedOrError(onCompleted, onError, errors) {
if (errors.length) {
onError(errors);
} else {
onCompleted();
}
};
},{}],30:[function(require,module,exports){
/**
* will onNext the observer with the seeds provided.
* @param {Model} model
* @param {Function} onNext
* @param {Array.<Object>} seeds
* @param {Function} [selector]
*/
module.exports = function onNextValues(model, onNext, seeds, selector) {
var root = model._root;
root.allowSync++;
try {
if (selector) {
if (seeds.length) {
// they should be wrapped in json items
onNext(selector.apply(model, seeds.map(function(x, i) {
return x.json;
})));
} else {
onNext(selector.call(model));
}
} else {
// this means there is an onNext function that is not AsValues or progressive,
// therefore there must only be one onNext call, which should only be the 0
// index of the values of the array
onNext(seeds[0]);
}
} catch(e) {
} finally {
root.allowSync--;
}
};
},{}],31:[function(require,module,exports){
var buildJSONGOperation = require('./buildJSONGOperation');
/**
* It performs the opposite of combine operations. It will take a JSONG
* response and partition them into the required amount of operations.
* @param {{jsong: {}, paths:[]}} jsongResponse
*/
module.exports = partitionOperations;
function partitionOperations(
jsongResponse, seeds, format, onNext) {
var partitionedOps = [];
var requestedMissingPaths = jsongResponse.paths;
if (format === 'AsJSON') {
// fast collapse ass the requestedMissingPaths into their
// respective groups
var opsFromRequestedMissingPaths = [];
var op = null;
for (var i = 0, len = requestedMissingPaths.length; i < len; i++) {
var missingPath = requestedMissingPaths[i];
if (!op || op.idx !== missingPath.pathSetIndex) {
op = {
idx: missingPath.pathSetIndex,
paths: []
};
opsFromRequestedMissingPaths.push(op);
}
op.paths.push(missingPath);
}
opsFromRequestedMissingPaths.forEach(function(op, i) {
var seed = [seeds[op.idx]];
var jsong = {
jsong: jsongResponse.jsong,
paths: op.paths
};
partitionedOps.push(buildJSONGOperation(
format,
seed,
jsong,
op.idx,
onNext));
});
} else {
partitionedOps[0] = buildJSONGOperation(format, seeds, jsongResponse, 0, onNext);
}
return partitionedOps;
}
},{"./buildJSONGOperation":22}],32:[function(require,module,exports){
module.exports = function primeSeeds(selector, selectorLength) {
var seeds = [];
if (selector) {
for (i = 0; i < selectorLength; i++) {
seeds.push({});
}
} else {
seeds[0] = {};
}
return seeds;
};
},{}],33:[function(require,module,exports){
module.exports = function processOperations(model, operations, errorSelector, boundPath) {
return operations.reduce(function(memo, operation) {
var jsonGraphOperation = model[operation.methodName];
var seedsOrFunction = operation.isValues ?
operation.onNext : operation.seeds;
var results = jsonGraphOperation(
model,
operation.args,
seedsOrFunction,
operation.onNext,
errorSelector,
boundPath);
var missing = results.requestedMissingPaths;
var offset = operation.seedsOffset;
for (var i = 0, len = missing.length; i < len; i++) {
missing[i].boundPath = boundPath;
missing[i].pathSetIndex += offset;
}
memo.requestedMissingPaths = memo.requestedMissingPaths.concat(missing);
memo.optimizedMissingPaths = memo.optimizedMissingPaths.concat(results.optimizedMissingPaths);
memo.errors = memo.errors.concat(results.errors);
memo.valuesReceived = memo.valuesReceived || results.requestedPaths.length > 0;
return memo;
}, {
errors: [],
requestedMissingPaths: [],
optimizedMissingPaths: [],
valuesReceived: false
});
}
},{}],34:[function(require,module,exports){
module.exports = function isSeedRequired(format) {
return format === 'AsJSON' || format === 'AsJSONG' || format === 'AsPathMap';
};
},{}],35:[function(require,module,exports){
module.exports = function setSeedsOnGroups(groups, seeds, hasSelector) {
var valueIndex = 0;
var seedsLength = seeds.length;
var j, i, len = groups.length, gLen, group;
if (hasSelector) {
for (i = 0; i < len && valueIndex < seedsLength; i++) {
group = groups[i];
gLen = gLen = group.args.length;
for (j = 0; j < gLen && valueIndex < seedsLength; j++, valueIndex++) {
group.seeds.push(seeds[valueIndex]);
}
}
} else {
for (i = 0; i < len && valueIndex < seedsLength; i++) {
groups[i].seeds = seeds;
}
}
}
},{}],36:[function(require,module,exports){
var setSeedsOnGroups = require('./setSeedsOnGroups');
module.exports = function setSeedsOrOnNext(operations, seedRequired, seeds, onNext, selector) {
if (seedRequired) {
setSeedsOnGroups(operations, seeds, selector);
} else {
for (i = 0; i < operations.length; i++) {
operations[i].onNext = onNext;
}
}
};
},{"./setSeedsOnGroups":35}],37:[function(require,module,exports){
var falcor = require('./../Falcor');
var NOOP = falcor.NOOP;
var RequestQueue = function(jsongModel, scheduler) {
this._scheduler = scheduler;
this._jsongModel = jsongModel;
this._scheduled = false;
this._requests = [];
};
RequestQueue.prototype = {
_get: function() {
var i = -1;
var requests = this._requests;
while (++i < requests.length) {
if (!requests[i].pending && requests[i].isGet) {
return requests[i];
}
}
return requests[requests.length] = new GetRequest(this._jsongModel, this);
},
_set: function() {
var i = -1;
var requests = this._requests;
// TODO: Set always sends off a request immediately, so there is no batching.
while (++i < requests.length) {
if (!requests[i].pending && requests[i].isSet) {
return requests[i];
}
}
return requests[requests.length] = new SetRequest(this._jsongModel, this);
},
remove: function(request) {
for (var i = this._requests.length - 1; i > -1; i--) {
if (this._requests[i].id === request.id && this._requests.splice(i, 1)) {
break;
}
}
},
set: function(jsongEnv, observer) {
var self = this;
var disposable = self._set().batch(jsongEnv, observer).flush();
return {
dispose: function() {
disposable.dispose();
}
};
},
get: function(requestedPaths, optimizedPaths, observer) {
var self = this;
var disposable = null;
// TODO: get does not batch across requests.
self._get().batch(requestedPaths, optimizedPaths, observer);
if (!self._scheduled) {
self._scheduled = true;
disposable = self._scheduler.schedule(self._flush.bind(self));
}
return {
dispose: function() {
disposable.dispose();
}
};
},
_flush: function() {
this._scheduled = false;
var requests = this._requests, i = -1;
var disposables = [];
while (++i < requests.length) {
if (!requests[i].pending) {
disposables[disposables.length] = requests[i].flush();
}
}
return {
dispose: function() {
disposables.forEach(function(d) { d.dispose(); });
}
};
}
};
var REQUEST_ID = 0;
var SetRequest = function(model, queue) {
var self = this;
self._jsongModel = model;
self._queue = queue;
self.observers = [];
self.jsongEnvs = [];
self.pending = false;
self.id = ++REQUEST_ID;
self.isSet = true;
};
SetRequest.prototype = {
batch: function(jsongEnv, observer) {
var self = this;
observer.onNext = observer.onNext || NOOP;
observer.onError = observer.onError || NOOP;
observer.onCompleted = observer.onCompleted || NOOP;
if (!observer.__observerId) {
observer.__observerId = ++REQUEST_ID;
}
observer._requestId = self.id;
self.observers[self.observers.length] = observer;
self.jsongEnvs[self.jsongEnvs.length] = jsongEnv;
return self;
},
flush: function() {
var incomingValues, query, op, len;
var self = this;
var jsongs = self.jsongEnvs;
var observers = self.observers;
var model = self._jsongModel;
self.pending = true;
// TODO: Set does not batch.
return model._dataSource.
set(jsongs[0]).
subscribe(function(response) {
incomingValues = response;
}, function(err) {
var i = -1;
var n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onError && obs.onError(err);
}
}, function() {
var i, n, obs;
self._queue.remove(self);
i = -1;
n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onNext && obs.onNext({
jsong: incomingValues.jsong || incomingValues.value,
paths: incomingValues.paths
});
obs.onCompleted && obs.onCompleted();
}
});
}
};
var GetRequest = function(jsongModel, queue) {
var self = this;
self._jsongModel = jsongModel;
self._queue = queue;
self.observers = [];
self.optimizedPaths = [];
self.requestedPaths = [];
self.pending = false;
self.id = ++REQUEST_ID;
self.isGet = true;
};
GetRequest.prototype = {
batch: function(requestedPaths, optimizedPaths, observer) {
// TODO: Do we need to gap fill?
var self = this;
observer.onNext = observer.onNext || NOOP;
observer.onError = observer.onError || NOOP;
observer.onCompleted = observer.onCompleted || NOOP;
if (!observer.__observerId) {
observer.__observerId = ++REQUEST_ID;
}
observer._requestId = self.id;
self.observers[self.observers.length] = observer;
self.optimizedPaths[self.optimizedPaths.length] = optimizedPaths;
self.requestedPaths[self.requestedPaths.length] = requestedPaths;
return self;
},
flush: function() {
var incomingValues, query, op, len;
var self = this;
var requested = self.requestedPaths;
var optimized = self.optimizedPaths;
var observers = self.observers;
var disposables = [];
var results = [];
var model = self._jsongModel;
self._scheduled = false;
self.pending = true;
var optimizedMaps = {};
var requestedMaps = {};
var r, o, i, j, obs, resultIndex;
for (i = 0, len = requested.length; i < len; i++) {
r = requested[i];
o = optimized[i];
obs = observers[i];
for (j = 0; j < r.length; j++) {
pathsToMapWithObservers(r[j], 0, readyNode(requestedMaps, null, obs), obs);
pathsToMapWithObservers(o[j], 0, readyNode(optimizedMaps, null, obs), obs);
}
}
return model._dataSource.
get(collapse(optimizedMaps)).
subscribe(function(response) {
incomingValues = response;
}, function(err) {
var i = -1;
var n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onError && obs.onError(err);
}
}, function() {
var i, n, obs;
self._queue.remove(self);
i = -1;
n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onNext && obs.onNext({
jsong: incomingValues.jsong || incomingValues.value,
paths: incomingValues.paths
});
obs.onCompleted && obs.onCompleted();
}
});
},
// Returns the paths that are contained within this request.
contains: function(requestedPaths, optimizedPaths) {
// TODO:
}
};
function pathsToMapWithObservers(path, idx, branch, observer) {
var curr = path[idx];
// Object / Array
if (typeof curr === 'object') {
if (Array.isArray(curr)) {
curr.forEach(function(v) {
readyNode(branch, v, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[v], observer);
}
});
} else {
var from = curr.from || 0;
var to = curr.to >= 0 ? curr.to : curr.length;
for (var i = from; i <= to; i++) {
readyNode(branch, i, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[i], observer);
}
}
}
} else {
readyNode(branch, curr, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[curr], observer);
}
}
}
/**
* Builds the set of collapsed
* queries by traversing the tree
* once
*/
var charPattern = /\D/i;
function readyNode(branch, key, observer) {
if (key === null) {
branch.__observers = branch.__observers || [];
!containsObserver(branch.__observers, observer) && branch.__observers.push(observer);
return branch;
}
if (!branch[key]) {
branch[key] = {__observers: []};
}
!containsObserver(branch[key].__observers, observer) && branch[key].__observers.push(observer);
return branch;
}
function containsObserver(observers, observer) {
if (!observer) {
return;
}
return observers.reduce(function(acc, x) {
return acc || x.__observerId === observer.__observerId;
}, false);
}
function collapse(pathMap) {
return rangeCollapse(buildQueries(pathMap));
}
/**
* Collapse ranges, e.g. when there is a continuous range
* in an array, turn it into an object instead
*
* [1,2,3,4,5,6] => {"from":1, "to":6}
*
*/
function rangeCollapse(paths) {
paths.forEach(function (path) {
path.forEach(function (elt, index) {
var range;
if (Array.isArray(elt) && elt.every(isNumber) && allUnique(elt)) {
elt.sort(function(a, b) {
return a - b;
});
if (elt[elt.length-1] - elt[0] === elt.length-1) {
// create range
range = {};
range.from = elt[0];
range.to = elt[elt.length-1];
path[index] = range;
}
}
});
});
return paths;
}
/* jshint forin: false */
function buildQueries(root) {
if (root == null || typeof root !== 'object') {
return [ [] ];
}
var children = Object.keys(root).filter(notPathMapInternalKeys),
child, memo, paths, key, childIsNum,
list, head, tail, clone, results,
i = -1, n = children.length,
j, k, x;
if (n === 0 || Array.isArray(root) === true) {
return [ [] ];
}
memo = {};
while(++i < n) {
child = children[i];
paths = buildQueries(root[child]);
key = createKey(paths);
childIsNum = typeof child === 'string' && !charPattern.test(child);
if ((list = memo[key]) && (head = list.head)) {
head[head.length] = childIsNum ? parseInt(child, 10) : child;
} else {
memo[key] = {
head: [childIsNum ? parseInt(child, 10) : child],
tail: paths
};
}
}
results = [];
for(x in memo) {
head = (list = memo[x]).head;
tail = list.tail;
i = -1;
n = tail.length;
while(++i < n) {
list = tail[i];
j = -1;
k = list.length;
if(head[0] === '') {
clone = [];
} else {
clone = [head.length === 1 ? head[0] : head];
while(++j < k) {
clone[j + 1] = list[j];
}
}
results[results.length] = clone;
}
}
return results;
}
function notPathMapInternalKeys(key) {
return (
key !== "__observers" &&
key !== "__pending" &&
key !== "__batchID"
);
}
/**
* Return true if argument is a number
*/
function isNumber(val) {
return typeof val === "number";
}
/**
* allUnique
* return true if every number in an array is unique
*/
function allUnique(arr) {
var hash = {},
index,
len;
for (index = 0, len = arr.length; index < len; index++) {
if (hash[arr[index]]) {
return false;
}
hash[arr[index]] = true;
}
return true;
}
/**
* Sort a list-of-lists
* Used for generating a unique hash
* key for each subtree; used by the
* memoization
*/
function sortLol(lol) {
return lol.reduce(function (result, curr) {
if (curr instanceof Array) {
result.push(sortLol(curr).slice(0).sort());
return result;
}
return result.concat(curr);
}, []).slice(0).sort();
}
/**
* Create a unique hash key for a set
* of paths
*/
function createKey(list) {
return JSON.stringify(sortLol(list));
}
// Note: For testing
falcor.__Internals.buildQueries = buildQueries;
module.exports = RequestQueue;
},{"./../Falcor":3}],38:[function(require,module,exports){
function ImmediateScheduler() {
}
ImmediateScheduler.prototype = {
schedule: function(action) {
action();
}
};
module.exports = ImmediateScheduler;
},{}],39:[function(require,module,exports){
function TimeoutScheduler(delay) {
this.delay = delay;
}
TimeoutScheduler.prototype = {
schedule: function(action) {
setTimeout(action, this.delay);
}
};
module.exports = TimeoutScheduler;
},{}],40:[function(require,module,exports){
var hardLink = require('./util/hardlink');
var createHardlink = hardLink.create;
var onValue = require('./onValue');
var isExpired = require('./util/isExpired');
var $path = require('./../types/path.js');
var __context = require("../internal/context");
function followReference(model, root, node, referenceContainer, reference, seed, outputFormat) {
var depth = 0;
var k, next;
while (true) {
if (depth === 0 && referenceContainer[__context]) {
depth = reference.length;
next = referenceContainer[__context];
} else {
k = reference[depth++];
next = node[k];
}
if (next) {
var type = next.$type;
var value = type && next.value || next;
if (depth < reference.length) {
if (type) {
node = next;
break;
}
node = next;
continue;
}
// We need to report a value or follow another reference.
else {
node = next;
if (type && isExpired(next)) {
break;
}
if (!referenceContainer[__context]) {
createHardlink(referenceContainer, next);
}
// Restart the reference follower.
if (type === $path) {
if (outputFormat === 'JSONG') {
onValue(model, next, seed, null, null, reference, null, outputFormat);
}
depth = 0;
reference = value;
referenceContainer = next;
node = root;
continue;
}
break;
}
} else {
node = undefined;
}
break;
}
if (depth < reference.length && node !== undefined) {
var ref = [];
for (var i = 0; i < depth; i++) {
ref[i] = reference[i];
}
reference = ref;
}
return [node, reference];
}
module.exports = followReference;
},{"../internal/context":62,"./../types/path.js":136,"./onValue":52,"./util/hardlink":54,"./util/isExpired":55}],41:[function(require,module,exports){
var getBoundValue = require('./getBoundValue');
var isPathValue = require('./util/isPathValue');
module.exports = function(walk) {
return function getAsJSON(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var requestedMissingPaths = results.requestedMissingPaths;
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var missingIdx = 0;
var boundOptimizedPath, optimizedPath;
var i, j, len, bLen;
results.values = values;
if (!values) {
values = [];
}
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (i = 0, len = paths.length; i < len; i++) {
var valueNode = undefined;
var pathSet = paths[i];
if (values[i]) {
valueNode = values[i];
}
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, 'JSON');
if (missingIdx < requestedMissingPaths.length) {
for (j = missingIdx, length = requestedMissingPaths.length; j < length; j++) {
requestedMissingPaths[j].pathSetIndex = i;
}
missingIdx = length;
}
}
return results;
};
};
},{"./getBoundValue":45,"./util/isPathValue":57}],42:[function(require,module,exports){
var getBoundValue = require('./getBoundValue');
var isPathValue = require('./util/isPathValue');
module.exports = function(walk) {
return function getAsJSONG(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
results.values = values;
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
if (boundPath.length) {
throw 'It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.';
} else {
currentCachePosition = cache;
}
for (var i = 0, len = paths.length; i < len; i++) {
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, values[0], [], results, [], [], inputFormat, 'JSONG');
}
return results;
};
};
},{"./getBoundValue":45,"./util/isPathValue":57}],43:[function(require,module,exports){
var getBoundValue = require('./getBoundValue');
var isPathValue = require('./util/isPathValue');
module.exports = function(walk) {
return function getAsPathMap(model, paths, values) {
var valueNode;
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
valueNode = values[0];
results.values = values;
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, 'PathMap');
}
return results;
};
};
},{"./getBoundValue":45,"./util/isPathValue":57}],44:[function(require,module,exports){
var getBoundValue = require('./getBoundValue');
var isPathValue = require('./util/isPathValue');
module.exports = function(walk) {
return function getAsValues(model, paths, onNext) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, onNext, null, results, optimizedPath, [], inputFormat, 'Values');
}
return results;
};
};
},{"./getBoundValue":45,"./util/isPathValue":57}],45:[function(require,module,exports){
var getValueSync = require('./getValueSync');
module.exports = function getBoundValue(model, path) {
var boxed, value, shorted;
boxed = model._boxed;
model._boxed = true;
value = getValueSync(model, path.concat(null));
model._boxed = boxed;
path = value.optimizedPath;
shorted = value.shorted;
value = value.value;
while (path.length && path[path.length - 1] === null) {
path.pop();
}
return {
path: path,
value: value,
shorted: shorted
};
};
},{"./getValueSync":46}],46:[function(require,module,exports){
var followReference = require('./followReference');
var clone = require('./util/clone');
var isExpired = require('./util/isExpired');
var promote = require('./util/lru').promote;
var $path = require('./../types/path.js');
var $sentinel = require('./../types/sentinel.js');
var $error = require('./../types/error.js');
module.exports = function getValueSync(model, simplePath) {
var root = model._cache;
var len = simplePath.length;
var optimizedPath = [];
var shorted = false, shouldShort = false;
var depth = 0;
var key, i, next = root, type, curr = root, out, ref, refNode;
do {
key = simplePath[depth++];
if (key !== null) {
next = curr[key];
optimizedPath.push(key);
}
if (!next) {
out = undefined;
shorted = true;
break;
}
type = next.$type;
// Up to the last key we follow references
if (depth < len) {
if (type === $path) {
ref = followReference(model, root, root, next, next.value);
refNode = ref[0];
if (!refNode) {
out = undefined;
break;
}
type = refNode.$type;
next = refNode;
optimizedPath = ref[1];
}
if (type) {
break;
}
}
// If there is a value, then we have great success, else, report an undefined.
else {
out = next;
}
curr = next;
} while (next && depth < len);
if (depth < len) {
// Unfortunately, if all that follows are nulls, then we have not shorted.
for (i = depth; i < len; ++i) {
if (simplePath[depth] !== null) {
shouldShort = true;
break;
}
}
// if we should short or report value. Values are reported on nulls.
if (shouldShort) {
shorted = true;
out = undefined;
} else {
out = next;
}
for (i = depth; i < len; ++i) {
optimizedPath[optimizedPath.length] = simplePath[i];
}
}
// promotes if not expired
if (out) {
if (isExpired(out)) {
out = undefined;
} else {
promote(model, out);
}
}
if (out && out.$type === $error && !model._treatErrorsAsValues) {
throw {path: simplePath, value: out.value};
} else if (out && model._boxed) {
out = !!type ? clone(out) : out;
} else if (!out && model._materialized) {
out = {$type: $sentinel};
} else if (out) {
out = out.value;
}
return {
value: out,
shorted: shorted,
optimizedPath: optimizedPath
};
};
},{"./../types/error.js":135,"./../types/path.js":136,"./../types/sentinel.js":137,"./followReference":40,"./util/clone":53,"./util/isExpired":55,"./util/lru":58}],47:[function(require,module,exports){
var followReference = require('./followReference');
var onError = require('./onError');
var onMissing = require('./onMissing');
var onValue = require('./onValue');
var lru = require('./util/lru');
var hardLink = require('./util/hardlink');
var isMaterialized = require('./util/isMaterialzed');
var removeHardlink = hardLink.remove;
var splice = lru.splice;
var isExpired = require('./util/isExpired');
var permuteKey = require('./util/permuteKey');
var $path = require('./../types/path');
var $error = require('./../types/error');
var __invalidated = require("../internal/invalidated");
function walk(model, root, curr, pathOrJSON, depth, seedOrFunction, positionalInfo, outerResults, optimizedPath, requestedPath, inputFormat, outputFormat, fromReference) {
if ((!curr || curr && curr.$type) &&
evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference)) {
return;
}
// We continue the search to the end of the path/json structure.
else {
// Base case of the searching: Have we hit the end of the road?
// Paths
// 1) depth === path.length
// PathMaps (json input)
// 2) if its an object with no keys
// 3) its a non-object
var jsonQuery = inputFormat === 'JSON';
var atEndOfJSONQuery = false;
var k, i, len;
if (jsonQuery) {
// it has a $type property means we have hit a end.
if (pathOrJSON && pathOrJSON.$type) {
atEndOfJSONQuery = true;
}
// is it an object?
else if (pathOrJSON && typeof pathOrJSON === 'object') {
// A terminating condition
k = Object.keys(pathOrJSON);
if (k.length === 1) {
k = k[0];
}
}
// found a primitive, we hit the end.
else {
atEndOfJSONQuery = true;
}
} else {
k = pathOrJSON[depth];
}
// BaseCase: we have hit the end of our query without finding a 'leaf' node, therefore emit missing.
if (atEndOfJSONQuery || !jsonQuery && depth === pathOrJSON.length) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
return;
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
return;
}
var memo = {done: false};
var permutePosition = positionalInfo;
var permuteRequested = requestedPath;
var permuteOptimized = optimizedPath;
var asJSONG = outputFormat === 'JSONG';
var asJSON = outputFormat === 'JSON';
var isKeySet = false;
var hasChildren = false;
depth++;
var key;
if (k && typeof k === 'object') {
memo.isArray = Array.isArray(k);
memo.arrOffset = 0;
key = permuteKey(k, memo);
isKeySet = true;
// The complex key provided is actual empty
if (memo.done) {
return;
}
} else {
key = k;
memo.done = true;
}
if (asJSON && isKeySet) {
permutePosition = [];
for (i = 0, len = positionalInfo.length; i < len; i++) {
permutePosition[i] = positionalInfo[i];
}
permutePosition.push(depth - 1);
}
do {
fromReference = false;
if (!memo.done) {
permuteOptimized = [];
permuteRequested = [];
for (i = 0, len = requestedPath.length; i < len; i++) {
permuteRequested[i] = requestedPath[i];
}
for (i = 0, len = optimizedPath.length; i < len; i++) {
permuteOptimized[i] = optimizedPath[i];
}
}
var nextPathOrPathMap = jsonQuery ? pathOrJSON[key] : pathOrJSON;
if (jsonQuery && nextPathOrPathMap) {
if (typeof nextPathOrPathMap === 'object') {
if (nextPathOrPathMap.$type) {
hasChildren = false;
} else {
hasChildren = Object.keys(nextPathOrPathMap).length > 0;
}
}
}
var next;
if (key === null || jsonQuery && key === '__null') {
next = curr;
} else {
next = curr[key];
permuteOptimized.push(key);
permuteRequested.push(key);
}
if (next) {
var nType = next.$type;
var value = nType && next.value || next;
if (jsonQuery && hasChildren || !jsonQuery && depth < pathOrJSON.length) {
if (nType && nType === $path && !isExpired(next)) {
if (asJSONG) {
onValue(model, next, seedOrFunction, outerResults, false, permuteOptimized, permutePosition, outputFormat);
}
var ref = followReference(model, root, root, next, value, seedOrFunction, outputFormat);
fromReference = true;
next = ref[0];
var refPath = ref[1];
permuteOptimized = [];
for (i = 0, len = refPath.length; i < len; i++) {
permuteOptimized[i] = refPath[i];
}
}
}
}
walk(model, root, next, nextPathOrPathMap, depth, seedOrFunction, permutePosition, outerResults, permuteOptimized, permuteRequested, inputFormat, outputFormat, fromReference);
if (!memo.done) {
key = permuteKey(k, memo);
}
} while (!memo.done);
}
}
function evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference) {
// BaseCase: This position does not exist, emit missing.
if (!curr) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
}
return true;
}
var currType = curr.$type;
positionalInfo = positionalInfo || [];
// The Base Cases. There is a type, therefore we have hit a 'leaf' node.
if (currType === $error) {
if (fromReference) {
requestedPath.push(null);
}
if (outputFormat === 'JSONG' || model._treatErrorsAsValues) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onError(model, curr, requestedPath, optimizedPath, outerResults);
}
}
// Else we have found a value, emit the current position information.
else {
if (isExpired(curr)) {
if (!curr[__invalidated]) {
splice(model, curr);
removeHardlink(curr);
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
} else {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
}
}
return true;
}
module.exports = walk;
},{"../internal/invalidated":65,"./../types/error":135,"./../types/path":136,"./followReference":40,"./onError":50,"./onMissing":51,"./onValue":52,"./util/hardlink":54,"./util/isExpired":55,"./util/isMaterialzed":56,"./util/lru":58,"./util/permuteKey":59}],48:[function(require,module,exports){
var walk = require('./getWalk');
module.exports = {
getAsJSON: require('./getAsJSON')(walk),
getAsJSONG: require('./getAsJSONG')(walk),
getAsValues: require('./getAsValues')(walk),
getAsPathMap: require('./getAsPathMap')(walk),
getValueSync: require('./getValueSync'),
getBoundValue: require('./getBoundValue'),
setCache: require('./legacy_setCache')
};
},{"./getAsJSON":41,"./getAsJSONG":42,"./getAsPathMap":43,"./getAsValues":44,"./getBoundValue":45,"./getValueSync":46,"./getWalk":47,"./legacy_setCache":49}],49:[function(require,module,exports){
/* istanbul ignore next */
var NOOP = function NOOP() {},
__GENERATION_GUID = 0,
__GENERATION_VERSION = 0,
__CONTAINER = "__reference_container",
__CONTEXT = "__context",
__GENERATION = "__generation",
__GENERATION_UPDATED = "__generation_updated",
__INVALIDATED = "__invalidated",
__KEY = "__key",
__KEYS = "__keys",
__IS_KEY_SET = "__is_key_set",
__NULL = "__null",
__SELF = "./",
__PARENT = "../",
__REF = "__ref",
__REF_INDEX = "__ref_index",
__REFS_LENGTH = "__refs_length",
__ROOT = "/",
__OFFSET = "__offset",
__FALKOR_EMPTY_OBJECT = '__FALKOR_EMPTY_OBJECT',
__INTERNAL_KEYS = [
__CONTAINER, __CONTEXT, __GENERATION, __GENERATION_UPDATED,
__INVALIDATED, __KEY, __KEYS, __IS_KEY_SET, __NULL, __SELF,
__PARENT, __REF, __REF_INDEX, __REFS_LENGTH, __OFFSET, __ROOT
],
$TYPE = "$type",
$SIZE = "$size",
$EXPIRES = "$expires",
$TIMESTAMP = "$timestamp",
SENTINEL = "sentinel",
PATH = "ref",
ERROR = "error",
VALUE = "value",
EXPIRED = "expired",
LEAF = "leaf";
/* istanbul ignore next */
module.exports = function setCache(model, map) {
var root = model._root, expired = root.expired, depth = 0, height = 0, mapStack = [], nodes = [], nodeRoot = model._cache, nodeParent = nodeRoot, node = nodeParent, nodeType, nodeValue, nodeSize, nodeTimestamp, nodeExpires;
mapStack[0] = map;
nodes[-1] = nodeParent;
while (depth > -1) {
/* Walk Path Map */
var isTerminus = false, offset = 0, keys = void 0, index = void 0, key = void 0, isKeySet = false;
node = nodeParent = nodes[depth - 1];
depth = depth;
follow_path_map_9177:
do {
height = depth;
nodeType = node && node[$TYPE] || void 0;
nodeValue = nodeType === SENTINEL ? node[VALUE] : node;
if ((isTerminus = !((map = mapStack[offset = depth * 4]) != null && typeof map === 'object') || map[$TYPE] !== void 0 || Array.isArray(map) || !((keys = mapStack[offset + 1] || (mapStack[offset + 1] = Object.keys(map))) && ((index = mapStack[offset + 2] || (mapStack[offset + 2] = 0)) || true) && ((isKeySet = keys.length > 1) || keys.length > 0))) || (node == null || nodeType !== void 0 || typeof node !== 'object' || Array.isArray(nodeValue))) {
if ((nodeExpires = (node && node[$EXPIRES]) != null) && (nodeExpires !== 1 && (nodeExpires === 0 || nodeExpires < now())) || node != null && node[__INVALIDATED] === true) {
nodeType = void 0;
nodeValue = void 0;
node = (expired[expired.length] = node) && (node[__INVALIDATED] = true) && void 0;
}
if (!isTerminus && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue))) {
if (node == null || nodeType !== void 0 || typeof node !== 'object' || Array.isArray(nodeValue)) {
key = null;
node = node;
depth = depth;
continue follow_path_map_9177;
}
} else {
if (key != null) {
var newNode, sizeOffset, edgeSize = node && node[$SIZE] || 0;
nodeType = map && map[$TYPE] || void 0;
nV2 = nodeType ? map[VALUE] : void 0;
nodeValue = nodeType === SENTINEL ? map[VALUE] : map;
newNode = map;
if ((!nodeType || nodeType === SENTINEL || nodeType === PATH) && Array.isArray(nodeValue)) {
delete nodeValue[$SIZE];
// console.log(1);
if (nodeType) {
nodeSize = 50 + (nodeValue.length || 1);
} else {
nodeSize = nodeValue.length || 1;
}
newNode[$SIZE] = nodeSize;
nodeValue[__CONTAINER] = newNode;
} else if (nodeType === SENTINEL || nodeType === PATH) {
newNode[$SIZE] = nodeSize = 50 + (nV2 && typeof nV2.length === 'number' ? nV2.length : 1);
} else if (nodeType === ERROR) {
newNode[$SIZE] = nodeSize = map && map[$SIZE] || 0 || 50 + 1;
} else if (!(map != null && typeof map === 'object')) {
nodeSize = 50 + (typeof nodeValue === 'string' && nodeValue.length || 1);
nodeType = 'sentinel';
newNode = {};
newNode[VALUE] = nodeValue;
newNode[$TYPE] = nodeType;
newNode[$SIZE] = nodeSize;
} else {
nodeType = newNode[$TYPE] = nodeType || GROUP;
newNode[$SIZE] = nodeSize = map && map[$SIZE] || 0 || 50 + 1;
}
;
if (node !== newNode && (node != null && typeof node === 'object')) {
var nodeRefsLength = node[__REFS_LENGTH] || 0, destRefsLength = newNode[__REFS_LENGTH] || 0, i = -1, ref;
while (++i < nodeRefsLength) {
if ((ref = node[__REF + i]) !== void 0) {
ref[__CONTEXT] = newNode;
newNode[__REF + (destRefsLength + i)] = ref;
node[__REF + i] = void 0;
}
}
newNode[__REFS_LENGTH] = nodeRefsLength + destRefsLength;
node[__REFS_LENGTH] = ref = void 0;
var invParent = nodeParent, invChild = node, invKey = key, keys$2, index$2, offset$2, childType, childValue, isBranch, stack = [
nodeParent,
invKey,
node
], depth$2 = 0;
while (depth$2 > -1) {
nodeParent = stack[offset$2 = depth$2 * 8];
invKey = stack[offset$2 + 1];
node = stack[offset$2 + 2];
if ((childType = stack[offset$2 + 3]) === void 0 || (childType = void 0)) {
childType = stack[offset$2 + 3] = node && node[$TYPE] || void 0 || null;
}
childValue = stack[offset$2 + 4] || (stack[offset$2 + 4] = childType === SENTINEL ? node[VALUE] : node);
if ((isBranch = stack[offset$2 + 5]) === void 0) {
isBranch = stack[offset$2 + 5] = !childType && (node != null && typeof node === 'object') && !Array.isArray(childValue);
}
if (isBranch === true) {
if ((keys$2 = stack[offset$2 + 6]) === void 0) {
keys$2 = stack[offset$2 + 6] = [];
index$2 = -1;
for (var childKey in node) {
!(!(childKey[0] !== '_' || childKey[1] !== '_') || (childKey === __SELF || childKey === __PARENT || childKey === __ROOT) || childKey[0] === '$') && (keys$2[++index$2] = childKey);
}
}
index$2 = stack[offset$2 + 7] || (stack[offset$2 + 7] = 0);
if (index$2 < keys$2.length) {
stack[offset$2 + 7] = index$2 + 1;
stack[offset$2 = ++depth$2 * 8] = node;
stack[offset$2 + 1] = invKey = keys$2[index$2];
stack[offset$2 + 2] = node[invKey];
continue;
}
}
var ref$2 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination;
if (ref$2 && Array.isArray(ref$2)) {
destination = ref$2[__CONTEXT];
if (destination) {
var i$2 = (ref$2[__REF_INDEX] || 0) - 1, n = (destination[__REFS_LENGTH] || 0) - 1;
while (++i$2 <= n) {
destination[__REF + i$2] = destination[__REF + (i$2 + 1)];
}
destination[__REFS_LENGTH] = n;
ref$2[__REF_INDEX] = ref$2[__CONTEXT] = destination = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$3, i$3 = -1, n$2 = node[__REFS_LENGTH] || 0;
while (++i$3 < n$2) {
if ((ref$3 = node[__REF + i$3]) !== void 0) {
ref$3[__CONTEXT] = node[__REF + i$3] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$2 = root, head = root$2.__head, tail = root$2.__tail, next = node.__next, prev = node.__prev;
next != null && typeof next === 'object' && (next.__prev = prev);
prev != null && typeof prev === 'object' && (prev.__next = next);
node === head && (root$2.__head = root$2.__next = next);
node === tail && (root$2.__tail = root$2.__prev = prev);
node.__next = node.__prev = void 0;
head = tail = next = prev = void 0;
;
nodeParent[invKey] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
;
delete stack[offset$2 + 0];
delete stack[offset$2 + 1];
delete stack[offset$2 + 2];
delete stack[offset$2 + 3];
delete stack[offset$2 + 4];
delete stack[offset$2 + 5];
delete stack[offset$2 + 6];
delete stack[offset$2 + 7];
--depth$2;
}
nodeParent = invParent;
node = invChild;
}
nodeParent[key] = node = newNode;
nodeType = node && node[$TYPE] || void 0;
node = !node[__SELF] && ((node[__SELF] = node) || true) && ((node[__KEY] = key) || true) && ((node[__PARENT] = nodeParent) || true) && ((node[__ROOT] = nodeRoot) || true) && (node[__GENERATION] || (node[__GENERATION] = ++__GENERATION_GUID) && node) && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue) && (nodeValue[__CONTAINER] = node)) || node;
sizeOffset = edgeSize - nodeSize;
var self = nodeParent, child = node;
while (node = nodeParent) {
nodeParent = node[__PARENT];
if ((node[$SIZE] = (node[$SIZE] || 0) - sizeOffset) <= 0 && nodeParent) {
var ref$4 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination$2;
if (ref$4 && Array.isArray(ref$4)) {
destination$2 = ref$4[__CONTEXT];
if (destination$2) {
var i$4 = (ref$4[__REF_INDEX] || 0) - 1, n$3 = (destination$2[__REFS_LENGTH] || 0) - 1;
while (++i$4 <= n$3) {
destination$2[__REF + i$4] = destination$2[__REF + (i$4 + 1)];
}
destination$2[__REFS_LENGTH] = n$3;
ref$4[__REF_INDEX] = ref$4[__CONTEXT] = destination$2 = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$5, i$5 = -1, n$4 = node[__REFS_LENGTH] || 0;
while (++i$5 < n$4) {
if ((ref$5 = node[__REF + i$5]) !== void 0) {
ref$5[__CONTEXT] = node[__REF + i$5] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$3 = root, head$2 = root$3.__head, tail$2 = root$3.__tail, next$2 = node.__next, prev$2 = node.__prev;
next$2 != null && typeof next$2 === 'object' && (next$2.__prev = prev$2);
prev$2 != null && typeof prev$2 === 'object' && (prev$2.__next = next$2);
node === head$2 && (root$3.__head = root$3.__next = next$2);
node === tail$2 && (root$3.__tail = root$3.__prev = prev$2);
node.__next = node.__prev = void 0;
head$2 = tail$2 = next$2 = prev$2 = void 0;
;
nodeParent[node[__KEY]] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
} else if (node[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
var self$2 = node, stack$2 = [], depth$3 = 0, linkPaths, ref$6, i$6, k, n$5;
while (depth$3 > -1) {
if ((linkPaths = stack$2[depth$3]) === void 0) {
i$6 = k = -1;
n$5 = node[__REFS_LENGTH] || 0;
node[__GENERATION_UPDATED] = __GENERATION_VERSION;
node[__GENERATION] = ++__GENERATION_GUID;
if ((ref$6 = node[__PARENT]) !== void 0 && ref$6[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
stack$2[depth$3] = linkPaths = new Array(n$5 + 1);
linkPaths[++k] = ref$6;
} else if (n$5 > 0) {
stack$2[depth$3] = linkPaths = new Array(n$5);
}
while (++i$6 < n$5) {
if ((ref$6 = node[__REF + i$6]) !== void 0 && ref$6[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
linkPaths[++k] = ref$6;
}
}
}
if ((node = linkPaths && linkPaths.pop()) !== void 0) {
++depth$3;
} else {
stack$2[depth$3--] = void 0;
}
}
node = self$2;
}
}
nodeParent = self;
node = child;
}
;
node = node;
break follow_path_map_9177;
}
}
if ((key = keys[index]) == null) {
node = node;
break follow_path_map_9177;
} else if (key === __NULL && ((key = null) || true) || !(!(key[0] !== '_' || key[1] !== '_') || (key === __SELF || key === __PARENT || key === __ROOT) || key[0] === '$') && ((mapStack[(depth + 1) * 4] = map[key]) || true)) {
mapStack[(depth + 1) * 4 + 3] = key;
} else {
mapStack[offset + 2] = index + 1;
node = node;
depth = depth;
continue follow_path_map_9177;
}
nodes[depth - 1] = nodeParent = node;
if (key != null) {
node = nodeParent && nodeParent[key];
if (typeof map === 'object') {
for (var key$2 in map) {
key$2[0] === '$' && key$2 !== $SIZE && (nodeParent && (nodeParent[key$2] = map[key$2]) || true);
}
map = map[key];
}
var mapType = map && map[$TYPE] || void 0;
var mapValue = mapType === SENTINEL ? map[VALUE] : map;
if ((node == null || typeof node !== 'object' || !!nodeType && nodeType !== SENTINEL && !Array.isArray(nodeValue)) && (!mapType && (map != null && typeof map === 'object') && !Array.isArray(mapValue))) {
nodeType = void 0;
nodeValue = {};
nodeSize = node && node[$SIZE] || 0;
if (node !== nodeValue && (node != null && typeof node === 'object')) {
var nodeRefsLength$2 = node[__REFS_LENGTH] || 0, destRefsLength$2 = nodeValue[__REFS_LENGTH] || 0, i$7 = -1, ref$7;
while (++i$7 < nodeRefsLength$2) {
if ((ref$7 = node[__REF + i$7]) !== void 0) {
ref$7[__CONTEXT] = nodeValue;
nodeValue[__REF + (destRefsLength$2 + i$7)] = ref$7;
node[__REF + i$7] = void 0;
}
}
nodeValue[__REFS_LENGTH] = nodeRefsLength$2 + destRefsLength$2;
node[__REFS_LENGTH] = ref$7 = void 0;
var invParent$2 = nodeParent, invChild$2 = node, invKey$2 = key, keys$3, index$3, offset$3, childType$2, childValue$2, isBranch$2, stack$3 = [
nodeParent,
invKey$2,
node
], depth$4 = 0;
while (depth$4 > -1) {
nodeParent = stack$3[offset$3 = depth$4 * 8];
invKey$2 = stack$3[offset$3 + 1];
node = stack$3[offset$3 + 2];
if ((childType$2 = stack$3[offset$3 + 3]) === void 0 || (childType$2 = void 0)) {
childType$2 = stack$3[offset$3 + 3] = node && node[$TYPE] || void 0 || null;
}
childValue$2 = stack$3[offset$3 + 4] || (stack$3[offset$3 + 4] = childType$2 === SENTINEL ? node[VALUE] : node);
if ((isBranch$2 = stack$3[offset$3 + 5]) === void 0) {
isBranch$2 = stack$3[offset$3 + 5] = !childType$2 && (node != null && typeof node === 'object') && !Array.isArray(childValue$2);
}
if (isBranch$2 === true) {
if ((keys$3 = stack$3[offset$3 + 6]) === void 0) {
keys$3 = stack$3[offset$3 + 6] = [];
index$3 = -1;
for (var childKey$2 in node) {
!(!(childKey$2[0] !== '_' || childKey$2[1] !== '_') || (childKey$2 === __SELF || childKey$2 === __PARENT || childKey$2 === __ROOT) || childKey$2[0] === '$') && (keys$3[++index$3] = childKey$2);
}
}
index$3 = stack$3[offset$3 + 7] || (stack$3[offset$3 + 7] = 0);
if (index$3 < keys$3.length) {
stack$3[offset$3 + 7] = index$3 + 1;
stack$3[offset$3 = ++depth$4 * 8] = node;
stack$3[offset$3 + 1] = invKey$2 = keys$3[index$3];
stack$3[offset$3 + 2] = node[invKey$2];
continue;
}
}
var ref$8 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination$3;
if (ref$8 && Array.isArray(ref$8)) {
destination$3 = ref$8[__CONTEXT];
if (destination$3) {
var i$8 = (ref$8[__REF_INDEX] || 0) - 1, n$6 = (destination$3[__REFS_LENGTH] || 0) - 1;
while (++i$8 <= n$6) {
destination$3[__REF + i$8] = destination$3[__REF + (i$8 + 1)];
}
destination$3[__REFS_LENGTH] = n$6;
ref$8[__REF_INDEX] = ref$8[__CONTEXT] = destination$3 = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$9, i$9 = -1, n$7 = node[__REFS_LENGTH] || 0;
while (++i$9 < n$7) {
if ((ref$9 = node[__REF + i$9]) !== void 0) {
ref$9[__CONTEXT] = node[__REF + i$9] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$4 = root, head$3 = root$4.__head, tail$3 = root$4.__tail, next$3 = node.__next, prev$3 = node.__prev;
next$3 != null && typeof next$3 === 'object' && (next$3.__prev = prev$3);
prev$3 != null && typeof prev$3 === 'object' && (prev$3.__next = next$3);
node === head$3 && (root$4.__head = root$4.__next = next$3);
node === tail$3 && (root$4.__tail = root$4.__prev = prev$3);
node.__next = node.__prev = void 0;
head$3 = tail$3 = next$3 = prev$3 = void 0;
;
nodeParent[invKey$2] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
;
delete stack$3[offset$3 + 0];
delete stack$3[offset$3 + 1];
delete stack$3[offset$3 + 2];
delete stack$3[offset$3 + 3];
delete stack$3[offset$3 + 4];
delete stack$3[offset$3 + 5];
delete stack$3[offset$3 + 6];
delete stack$3[offset$3 + 7];
--depth$4;
}
nodeParent = invParent$2;
node = invChild$2;
}
nodeParent[key] = node = nodeValue;
node = !node[__SELF] && ((node[__SELF] = node) || true) && ((node[__KEY] = key) || true) && ((node[__PARENT] = nodeParent) || true) && ((node[__ROOT] = nodeRoot) || true) && (node[__GENERATION] || (node[__GENERATION] = ++__GENERATION_GUID) && node) && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue) && (nodeValue[__CONTAINER] = node)) || node;
var self$3 = node, node$2;
while (node$2 = node) {
if (node[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
var self$4 = node, stack$4 = [], depth$5 = 0, linkPaths$2, ref$10, i$10, k$2, n$8;
while (depth$5 > -1) {
if ((linkPaths$2 = stack$4[depth$5]) === void 0) {
i$10 = k$2 = -1;
n$8 = node[__REFS_LENGTH] || 0;
node[__GENERATION_UPDATED] = __GENERATION_VERSION;
node[__GENERATION] = ++__GENERATION_GUID;
if ((ref$10 = node[__PARENT]) !== void 0 && ref$10[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
stack$4[depth$5] = linkPaths$2 = new Array(n$8 + 1);
linkPaths$2[++k$2] = ref$10;
} else if (n$8 > 0) {
stack$4[depth$5] = linkPaths$2 = new Array(n$8);
}
while (++i$10 < n$8) {
if ((ref$10 = node[__REF + i$10]) !== void 0 && ref$10[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
linkPaths$2[++k$2] = ref$10;
}
}
}
if ((node = linkPaths$2 && linkPaths$2.pop()) !== void 0) {
++depth$5;
} else {
stack$4[depth$5--] = void 0;
}
}
node = self$4;
}
node = node$2[__PARENT];
}
node = self$3;
}
}
node = node;
depth = depth + 1;
continue follow_path_map_9177;
} while (true);
node = node;
var offset$4 = depth * 4, keys$4, index$4;
do {
delete mapStack[offset$4 + 0];
delete mapStack[offset$4 + 1];
delete mapStack[offset$4 + 2];
delete mapStack[offset$4 + 3];
} while ((keys$4 = mapStack[(offset$4 = 4 * --depth) + 1]) && ((index$4 = mapStack[offset$4 + 2]) || true) && (mapStack[offset$4 + 2] = ++index$4) >= keys$4.length);
}
return nodeRoot;
}
},{}],50:[function(require,module,exports){
var lru = require('./util/lru');
var clone = require('./util/clone');
var promote = lru.promote;
module.exports = function onError(model, node, permuteRequested, permuteOptimized, outerResults) {
outerResults.errors.push({path: permuteRequested, value: node.value});
promote(model, node);
if (permuteOptimized) {
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
};
},{"./util/clone":53,"./util/lru":58}],51:[function(require,module,exports){
var support = require('./util/support');
var fastCat = support.fastCat,
fastCatSkipNulls = support.fastCatSkipNulls,
fastCopy = support.fastCopy;
var isExpired = require('./util/isExpired');
var spreadJSON = require('./util/spreadJSON');
var clone = require('./util/clone');
module.exports = function onMissing(model, node, path, depth, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat) {
var pathSlice;
if (Array.isArray(path)) {
if (depth < path.length) {
pathSlice = fastCopy(path, depth);
} else {
pathSlice = [];
}
concatAndInsertMissing(pathSlice, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat);
} else {
pathSlice = [];
spreadJSON(path, pathSlice);
for (var i = 0, len = pathSlice.length; i < len; i++) {
concatAndInsertMissing(pathSlice[i], outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, true);
}
}
};
function concatAndInsertMissing(remainingPath, results, permuteRequested, permuteOptimized, permutePosition, outputFormat, __null) {
var i = 0, len;
if (__null) {
for (i = 0, len = remainingPath.length; i < len; i++) {
if (remainingPath[i] === '__null') {
remainingPath[i] = null;
}
}
}
if (outputFormat === 'JSON') {
permuteRequested = fastCat(permuteRequested, remainingPath);
for (i = 0, len = permutePosition.length; i < len; i++) {
var idx = permutePosition[i];
var r = permuteRequested[idx];
permuteRequested[idx] = [r];
}
results.requestedMissingPaths.push(permuteRequested);
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
} else {
results.requestedMissingPaths.push(fastCat(permuteRequested, remainingPath));
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
}
}
},{"./util/clone":53,"./util/isExpired":55,"./util/spreadJSON":60,"./util/support":61}],52:[function(require,module,exports){
var lru = require('./util/lru');
var clone = require('./util/clone');
var promote = lru.promote;
var $path = require('./../types/path');
var $sentinel = require('./../types/sentinel');
var $error = require('./../types/error');
module.exports = function onValue(model, node, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, fromReference) {
var i, len, k, key, curr, prev, prevK;
var materialized = false, valueNode;
if (node) {
promote(model, node);
}
if (!node || node.value === undefined) {
materialized = model._materialized;
}
// materialized
if (materialized) {
valueNode = {$type: $sentinel};
}
// Boxed Mode & Reference Node & Error node (only happens when model is in treat errors as values).
else if (model._boxed) {
valueNode = clone(node);
}
else if (node.$type === $path || node.$type === $error) {
if (outputFormat === 'JSONG') {
valueNode = clone(node);
} else {
valueNode = node.value;
}
}
else {
if (outputFormat === 'JSONG') {
if (typeof node.value === 'object') {
valueNode = clone(node);
} else {
valueNode = node.value;
}
} else {
valueNode = node.value;
}
}
if (permuteRequested) {
if (fromReference && permuteRequested[permuteRequested.length - 1] !== null) {
permuteRequested.push(null);
}
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
switch (outputFormat) {
case 'Values':
// in any subscription situation, onNexts are always provided, even as a noOp.
seedOrFunction({path: permuteRequested, value: valueNode});
break;
case 'PathMap':
len = permuteRequested.length - 1;
if (len === -1) {
seedOrFunction.json = valueNode;
} else {
curr = seedOrFunction.json;
if (!curr) {
curr = seedOrFunction.json = {};
}
for (i = 0; i < len; i++) {
k = permuteRequested[i];
if (!curr[k]) {
curr[k] = {};
}
prev = curr;
prevK = k;
curr = curr[k];
}
k = permuteRequested[i];
if (k !== null) {
curr[k] = valueNode;
} else {
prev[prevK] = valueNode;
}
}
break;
case 'JSON':
if (seedOrFunction) {
if (permutePosition.length) {
if (!seedOrFunction.json) {
seedOrFunction.json = {};
}
curr = seedOrFunction.json;
for (i = 0, len = permutePosition.length - 1; i < len; i++) {
k = permutePosition[i];
key = permuteRequested[k];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
k = permutePosition[i];
key = permuteRequested[k];
curr[key] = valueNode;
} else {
seedOrFunction.json = valueNode;
}
}
break;
case 'JSONG':
curr = seedOrFunction.jsong;
if (!curr) {
curr = seedOrFunction.jsong = {};
seedOrFunction.paths = [];
}
for (i = 0, len = permuteOptimized.length - 1; i < len; i++) {
key = permuteOptimized[i];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
key = permuteOptimized[i];
// TODO: Special case? do string comparisons make big difference?
curr[key] = materialized ? {$type: $sentinel} : valueNode;
if (permuteRequested) {
seedOrFunction.paths.push(permuteRequested);
}
break;
}
};
},{"./../types/error":135,"./../types/path":136,"./../types/sentinel":137,"./util/clone":53,"./util/lru":58}],53:[function(require,module,exports){
// Copies the node
var prefix = require("../../internal/prefix");
module.exports = function clone(node) {
var outValue, i, len;
var keys = Object.keys(node);
outValue = {};
for (i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
if (k[0] === prefix) {
continue;
}
outValue[k] = node[k];
}
return outValue;
};
},{"../../internal/prefix":70}],54:[function(require,module,exports){
var __ref = require("../../internal/ref");
var __context = require("../../internal/context");
var __ref_index = require("../../internal/ref-index");
var __refs_length = require("../../internal/refs-length");
function createHardlink(from, to) {
// create a back reference
var backRefs = to[__refs_length] || 0;
to[__ref + backRefs] = from;
to[__refs_length] = backRefs + 1;
// create a hard reference
from[__ref_index] = backRefs;
from[__context] = to;
}
function removeHardlink(cacheObject) {
var context = cacheObject[__context];
if (context) {
var idx = cacheObject[__ref_index];
var len = context[__refs_length];
while (idx < len) {
context[__ref + idx] = context[__REF + idx + 1];
++idx;
}
context[__refs_length] = len - 1;
cacheObject[__context] = undefined;
cacheObject[__ref_index] = undefined;
}
}
module.exports = {
create: createHardlink,
remove: removeHardlink
};
},{"../../internal/context":62,"../../internal/ref":73,"../../internal/ref-index":72,"../../internal/refs-length":74}],55:[function(require,module,exports){
var now = require('../../support/now');
module.exports = function isExpired(node) {
var $expires = node.$expires === undefined && -1 || node.$expires;
return $expires !== -1 && $expires !== 1 && ($expires === 0 || $expires < now());
};
},{"../../support/now":122}],56:[function(require,module,exports){
module.exports = function isMaterialized(model) {
return model._materialized && !(model._router || model._dataSource);
};
},{}],57:[function(require,module,exports){
module.exports = function(x) {
return x.path && x.value;
};
},{}],58:[function(require,module,exports){
var __head = require("../../internal/head");
var __tail = require("../../internal/tail");
var __next = require("../../internal/next");
var __prev = require("../../internal/prev");
var __invalidated = require("../../internal/invalidated");
// [H] -> Next -> ... -> [T]
// [T] -> Prev -> ... -> [H]
function lruPromote(model, object) {
var root = model._root;
var head = root[__head];
if (head === object) {
return;
}
// First insert
if (!head) {
root[__head] = object;
return;
}
// The head and the tail need to separate
if (!root[__tail]) {
root[__head] = object;
root[__tail] = head;
object[__next] = head;
// Now tail
head[__prev] = object;
return;
}
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = undefined;
// Insert into head position
root[__head] = object;
object[__next] = head;
head[__prev] = object;
}
function lruSplice(model, object) {
var root = model._root;
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = undefined;
if (object === root[__head]) {
root[__head] = undefined;
}
if (object === root[__tail]) {
root[__tail] = undefined;
}
object[__invalidated] = true;
root.expired.push(object);
}
module.exports = {
promote: lruPromote,
splice: lruSplice
};
},{"../../internal/head":64,"../../internal/invalidated":65,"../../internal/next":67,"../../internal/prev":71,"../../internal/tail":75}],59:[function(require,module,exports){
var prefix = require("../../internal/prefix");
module.exports = function permuteKey(key, memo) {
if (memo.isArray) {
if (memo.loaded && memo.rangeOffset > memo.to) {
memo.arrOffset++;
memo.loaded = false;
}
var idx = memo.arrOffset, length = key.length;
if (idx === length) {
memo.done = true;
return '';
}
var el = key[memo.arrOffset];
var type = typeof el;
if (type === 'object') {
if (!memo.loaded) {
memo.from = el.from || 0;
memo.to = el.to ||
typeof el.length === 'number' && memo.from + el.length - 1 || 0;
memo.rangeOffset = memo.from;
memo.loaded = true;
}
return memo.rangeOffset++;
} else {
do {
// if (type !== 'string') {
// break;
// }
if (el[0] !== prefix && el[0] !== '$') {
break;
}
el = key[++idx];
} while (el !== undefined || idx < length);
if (el === undefined || idx === length) {
memo.done = true;
return '';
}
memo.arrOffset = idx + 1;
return el;
}
} else {
if (!memo.loaded) {
memo.from = key.from || 0;
memo.to = key.to ||
typeof key.length === 'number' && memo.from + key.length - 1 || 0;
memo.rangeOffset = memo.from;
memo.loaded = true;
}
if (memo.rangeOffset > memo.to) {
memo.done = true;
return '';
}
return memo.rangeOffset++;
}
};
},{"../../internal/prefix":70}],60:[function(require,module,exports){
var fastCopy = require('./support').fastCopy;
module.exports = function spreadJSON(root, bins, bin) {
bin = bin || [];
if (!bins.length) {
bins.push(bin);
}
if (!root || typeof root !== 'object' || root.$type) {
return [];
}
var keys = Object.keys(root);
if (keys.length === 1) {
bin.push(keys[0]);
spreadJSON(root[keys[0]], bins, bin);
} else {
for (var i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
var nextBin = fastCopy(bin);
nextBin.push(k);
bins.push(nextBin);
spreadJSON(root[k], bins, nextBin);
}
}
};
},{"./support":61}],61:[function(require,module,exports){
function fastCopy(arr, i) {
var a = [], len, j;
for (j = 0, i = i || 0, len = arr.length; i < len; j++, i++) {
a[j] = arr[i];
}
return a;
}
function fastCatSkipNulls(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
if (arr2[j] !== null) {
a[i++] = arr2[j];
}
}
return a;
}
function fastCat(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
a[i++] = arr2[j];
}
return a;
}
module.exports = {
fastCat: fastCat,
fastCatSkipNulls: fastCatSkipNulls,
fastCopy: fastCopy
};
},{}],62:[function(require,module,exports){
module.exports = require("./prefix") + "context";
},{"./prefix":70}],63:[function(require,module,exports){
module.exports = require("./prefix") + "generation";
},{"./prefix":70}],64:[function(require,module,exports){
module.exports = require("./prefix") + "head";
},{"./prefix":70}],65:[function(require,module,exports){
module.exports = require("./prefix") + "invalidated";
},{"./prefix":70}],66:[function(require,module,exports){
module.exports = require("./prefix") + "key";
},{"./prefix":70}],67:[function(require,module,exports){
module.exports = require("./prefix") + "next";
},{"./prefix":70}],68:[function(require,module,exports){
module.exports = require("./prefix") + "offset";
},{"./prefix":70}],69:[function(require,module,exports){
module.exports = require("./prefix") + "parent";
},{"./prefix":70}],70:[function(require,module,exports){
// This may look like an empty string, but it's actually a single zero-width-space character.
module.exports = "";
},{}],71:[function(require,module,exports){
module.exports = require("./prefix") + "prev";
},{"./prefix":70}],72:[function(require,module,exports){
module.exports = require("./prefix") + "ref-index";
},{"./prefix":70}],73:[function(require,module,exports){
module.exports = require("./prefix") + "ref";
},{"./prefix":70}],74:[function(require,module,exports){
module.exports = require("./prefix") + "refs-length";
},{"./prefix":70}],75:[function(require,module,exports){
module.exports = require("./prefix") + "tail";
},{"./prefix":70}],76:[function(require,module,exports){
module.exports = require("./prefix") + "version";
},{"./prefix":70}],77:[function(require,module,exports){
module.exports = {
invPathSetsAsJSON: require("./invalidate-path-sets-as-json-dense"),
invPathSetsAsJSONG: require("./invalidate-path-sets-as-json-graph"),
invPathSetsAsPathMap: require("./invalidate-path-sets-as-json-sparse"),
invPathSetsAsValues: require("./invalidate-path-sets-as-json-values")
};
},{"./invalidate-path-sets-as-json-dense":78,"./invalidate-path-sets-as-json-graph":79,"./invalidate-path-sets-as-json-sparse":80,"./invalidate-path-sets-as-json-values":81}],78:[function(require,module,exports){
module.exports = invalidate_path_sets_as_json_dense;
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var array_slice = require("../support/array-slice");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var update_graph = require("../support/update-graph");
var invalidate_node = require("../support/invalidate-node");
var collect = require("../lru/collect");
function invalidate_path_sets_as_json_dense(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots[3] = parents[3] = nodes[3] = undefined;
}
var pathset = pathsets[index];
roots.index = index;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
if (is_keyset && !!(parents[3] = json)) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
nodes[0] = node;
if (!!json) {
var type = is_object(node) && node.$type || undefined;
var jsonkey = keyset;
if (jsonkey == null) {
json = roots;
jsonkey = 3;
}
json[jsonkey] = clone(roots, node, type, node && node.value);
}
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
roots.json = roots[3];
roots.hasValue = true;
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/array-slice":101,"../support/clone-dense-json":102,"../support/get-valid-key":112,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/update-graph":133,"../walk/walk-path-set":143}],79:[function(require,module,exports){
module.exports = invalidate_path_sets_as_json_graph;
var $path = require("../types/path");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var update_graph = require("../support/update-graph");
var invalidate_node = require("../support/invalidate-node");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function invalidate_path_sets_as_json_graph(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var type = is_object(node) && node.$type || undefined;
if (is_branch) {
parents[0] = nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
clone_success(roots, requested, optimized);
roots.json = roots[1];
roots.hasValue = true;
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/update-graph":133,"../types/path":136,"../walk/walk-path-set-soft-link":142}],80:[function(require,module,exports){
module.exports = invalidate_path_sets_as_json_sparse;
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var array_slice = require("../support/array-slice");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var update_graph = require("../support/update-graph");
var invalidate_node = require("../support/invalidate-node");
var collect = require("../lru/collect");
function invalidate_path_sets_as_json_sparse(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
parents[3] = json;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
nodes[0] = node;
var type = is_object(node) && node.$type || undefined;
json[jsonkey] = clone(roots, node, type, node && node.value);
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
roots.json = roots[3];
roots.hasValue = true;
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/array-slice":101,"../support/clone-dense-json":102,"../support/get-valid-key":112,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/update-graph":133,"../walk/walk-path-set":143}],81:[function(require,module,exports){
module.exports = invalidate_path_sets_as_json_values;
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var array_slice = require("../support/array-slice");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var update_graph = require("../support/update-graph");
var invalidate_node = require("../support/invalidate-node");
var collect = require("../lru/collect");
function invalidate_path_sets_as_json_values(model, pathsets, onNext) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
return;
}
nodes[0] = node;
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || undefined;
var onNext = roots.onNext;
if (!!type && onNext) {
onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/array-slice":101,"../support/clone-dense-json":102,"../support/get-valid-key":112,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/update-graph":133,"../walk/walk-path-set":143}],82:[function(require,module,exports){
var __head = require("../internal/head");
var __tail = require("../internal/tail");
var __next = require("../internal/next");
var __prev = require("../internal/prev");
var update_graph = require("../support/update-graph");
module.exports = function(lru, expired, version, total, max, ratio) {
var targetSize = max * ratio;
var node, size;
while(!!(node = expired.pop())) {
size = node.$size || 0;
total -= size;
update_graph(node, size, version, lru);
}
if(total >= max) {
var prev = lru[__tail];
while((total >= targetSize) && !!(node = prev)) {
prev = prev[__prev];
size = node.$size || 0;
total -= size;
update_graph(node, size, version, lru);
}
if((lru[__tail] = lru[__prev] = prev) == null) {
lru[__head] = lru[__next] = undefined;
} else {
prev[__next] = undefined;
}
}
};
},{"../internal/head":64,"../internal/next":67,"../internal/prev":71,"../internal/tail":75,"../support/update-graph":133}],83:[function(require,module,exports){
var $expires_never = require("../values/expires-never");
var __head = require("../internal/head");
var __tail = require("../internal/tail");
var __next = require("../internal/next");
var __prev = require("../internal/prev");
var is_object = require("../support/is-object");
module.exports = function(root, node) {
if(is_object(node) && (node.$expires !== $expires_never)) {
var head = root[__head], tail = root[__tail],
next = node[__next], prev = node[__prev];
if (node !== head) {
(next != null && typeof next === "object") && (next[__prev] = prev);
(prev != null && typeof prev === "object") && (prev[__next] = next);
(next = head) && (head != null && typeof head === "object") && (head[__prev] = node);
(root[__head] = root[__next] = head = node);
(head[__next] = next);
(head[__prev] = undefined);
}
if (tail == null || node === tail) {
root[__tail] = root[__prev] = tail = prev || node;
}
}
return node;
};
},{"../internal/head":64,"../internal/next":67,"../internal/prev":71,"../internal/tail":75,"../support/is-object":118,"../values/expires-never":138}],84:[function(require,module,exports){
var __head = require("../internal/head");
var __tail = require("../internal/tail");
var __next = require("../internal/next");
var __prev = require("../internal/prev");
module.exports = function(root, node) {
var head = root[__head], tail = root[__tail],
next = node[__next], prev = node[__prev];
(next != null && typeof next === "object") && (next[__prev] = prev);
(prev != null && typeof prev === "object") && (prev[__next] = next);
(node === head) && (root[__head] = root[__next] = next);
(node === tail) && (root[__tail] = root[__prev] = prev);
node[__next] = node[__prev] = undefined;
head = tail = next = prev = undefined;
};
},{"../internal/head":64,"../internal/next":67,"../internal/prev":71,"../internal/tail":75}],85:[function(require,module,exports){
module.exports = {
setPathSetsAsJSON: require('./set-json-values-as-json-dense'),
setPathSetsAsJSONG: require('./set-json-values-as-json-graph'),
setPathSetsAsPathMap: require('./set-json-values-as-json-sparse'),
setPathSetsAsValues: require('./set-json-values-as-json-values'),
setPathMapsAsJSON: require('./set-json-sparse-as-json-dense'),
setPathMapsAsJSONG: require('./set-json-sparse-as-json-graph'),
setPathMapsAsPathMap: require('./set-json-sparse-as-json-sparse'),
setPathMapsAsValues: require('./set-json-sparse-as-json-values'),
setJSONGsAsJSON: require('./set-json-graph-as-json-dense'),
setJSONGsAsJSONG: require('./set-json-graph-as-json-graph'),
setJSONGsAsPathMap: require('./set-json-graph-as-json-sparse'),
setJSONGsAsValues: require('./set-json-graph-as-json-values'),
setCache: require('./set-cache')
};
},{"./set-cache":86,"./set-json-graph-as-json-dense":87,"./set-json-graph-as-json-graph":88,"./set-json-graph-as-json-sparse":89,"./set-json-graph-as-json-values":90,"./set-json-sparse-as-json-dense":91,"./set-json-sparse-as-json-graph":92,"./set-json-sparse-as-json-sparse":93,"./set-json-sparse-as-json-values":94,"./set-json-values-as-json-dense":95,"./set-json-values-as-json-graph":96,"./set-json-values-as-json-sparse":97,"./set-json-values-as-json-values":98}],86:[function(require,module,exports){
module.exports = set_cache;
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var collect = require("../lru/collect");
function set_cache(model, pathmap, error_selector) {
var roots = options([], model, error_selector);
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
roots[0] = roots.root;
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return model;
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key],
type;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/sentinel":137,"../walk/walk-path-map":141}],87:[function(require,module,exports){
module.exports = set_json_graph_as_json_dense;
var $path = require("../types/path");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var merge_node = require("../support/merge-node");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_graph_as_json_dense(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var index2 = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index3 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index3 < count2) {
json = values && values[++index2];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pathset = pathsets[index3];
roots.index = index3;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
messageParent = parents[2];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
var length = requested.length;
var offset = roots.offset;
parents[3] = json;
if (is_branch) {
parents[0] = node;
parents[2] = message;
if ((length > offset) && is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/is-object":118,"../support/merge-node":121,"../support/options":123,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../types/path":136,"../walk/walk-path-set-soft-link":142}],88:[function(require,module,exports){
module.exports = set_json_graph_as_json_graph;
var $path = require("../types/path");
var clone = require("../support/clone-graph-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var merge_node = require("../support/merge-node");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var promote = require("../lru/promote");
var collect = require("../lru/collect");
function set_json_graph_as_json_graph(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = 0;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
messageParent = parents[2];
} else {
json = nodes[1];
parent = nodes[0];
messageParent = nodes[2];
}
var jsonkey = key;
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
parents[1] = json;
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var type = is_object(node) && node.$type || undefined;
if (is_branch) {
parents[0] = node;
parents[2] = message;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":82,"../lru/promote":83,"../support/array-clone":100,"../support/clone-graph-json":103,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/is-object":118,"../support/merge-node":121,"../support/options":123,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../types/path":136,"../walk/walk-path-set-soft-link":142}],89:[function(require,module,exports){
module.exports = set_json_graph_as_json_sparse;
var $path = require("../types/path");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var merge_node = require("../support/merge-node");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_graph_as_json_sparse(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
messageParent = parents[2];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
parents[3] = json;
if (is_branch) {
var length = requested.length;
var offset = roots.offset;
var type = is_object(node) && node.$type || undefined;
parents[0] = node;
parents[2] = message;
if ((length > offset) && (!type || type == $path)) {
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/is-object":118,"../support/merge-node":121,"../support/options":123,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../types/path":136,"../walk/walk-path-set-soft-link":142}],90:[function(require,module,exports){
module.exports = set_json_graph_as_json_values;
var $path = require("../types/path");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var array_slice = require("../support/array-slice");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var merge_node = require("../support/merge-node");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_graph_as_json_values(model, envelopes, onNext, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset) {
var parent, messageParent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
messageParent = parents[2];
} else {
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
if (is_branch) {
parents[0] = node;
parents[2] = message;
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_slice(requested, roots.offset),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/array-slice":101,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/is-object":118,"../support/merge-node":121,"../support/options":123,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../types/path":136,"../walk/walk-path-set-soft-link":142}],91:[function(require,module,exports){
module.exports = set_json_sparse_as_json_dense;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-map");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_sparse_as_json_dense(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pathmap = pathmaps[index];
roots.index = index;
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
if (is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-map":129,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-map":141}],92:[function(require,module,exports){
module.exports = set_json_sparse_as_json_graph;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-graph-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-map");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var promote = require("../lru/promote");
var collect = require("../lru/collect");
function set_json_sparse_as_json_graph(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
type = node.$type;
parents[0] = nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":82,"../lru/promote":83,"../support/array-clone":100,"../support/clone-graph-json":103,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-map":129,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-map-soft-link":140}],93:[function(require,module,exports){
module.exports = set_json_sparse_as_json_sparse;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-map");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_sparse_as_json_sparse(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-map":129,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-map":141}],94:[function(require,module,exports){
module.exports = set_path_map_as_json_values;
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-map");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_path_map_as_json_values(model, pathmaps, onNext, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-map":129,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/sentinel":137,"../walk/walk-path-map":141}],95:[function(require,module,exports){
module.exports = set_json_values_as_json_dense;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var invalidate_node = require("../support/invalidate-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_values_as_json_dense(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
roots.index = index;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
if (is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-set":143}],96:[function(require,module,exports){
module.exports = set_json_values_as_json_graph;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-graph-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var invalidate_node = require("../support/invalidate-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var promote = require("../lru/promote");
var collect = require("../lru/collect");
function set_json_values_as_json_graph(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
type = node.$type;
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":82,"../lru/promote":83,"../support/array-clone":100,"../support/clone-graph-json":103,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-set-soft-link":142}],97:[function(require,module,exports){
module.exports = set_json_values_as_json_sparse;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var invalidate_node = require("../support/invalidate-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_values_as_json_sparse(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-set":143}],98:[function(require,module,exports){
module.exports = set_json_values_as_json_values;
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var invalidate_node = require("../support/invalidate-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_values_as_json_values(model, pathvalues, onNext, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized, nodes)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key], type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/sentinel":137,"../walk/walk-path-set":143}],99:[function(require,module,exports){
module.exports = function(array, value) {
var i = -1;
var n = array.length;
var array2 = new Array(n + 1);
while(++i < n) { array2[i] = array[i]; }
array2[i] = value;
return array2;
};
},{}],100:[function(require,module,exports){
module.exports = function(array) {
var i = -1;
var n = array.length;
var array2 = new Array(n);
while(++i < n) { array2[i] = array[i]; }
return array2;
};
},{}],101:[function(require,module,exports){
module.exports = function(array, index) {
var i = -1;
var n = array.length - index;
var array2 = new Array(n);
while(++i < n) { array2[i] = array[i + index]; }
return array2;
};
},{}],102:[function(require,module,exports){
var $sentinel = require("../types/sentinel");
var clone = require("./clone");
module.exports = function(roots, node, type, value) {
if(node == null || value === undefined) {
return { $type: $sentinel };
}
if(roots.boxed == true) {
return !!type && clone(node) || node;
}
return value;
}
},{"../types/sentinel":137,"./clone":109}],103:[function(require,module,exports){
var $sentinel = require("../types/sentinel");
var clone = require("./clone");
var is_primitive = require("./is-primitive");
module.exports = function(roots, node, type, value) {
if(node == null || value === undefined) {
return { $type: $sentinel };
}
if(roots.boxed == true) {
return !!type && clone(node) || node;
}
if(!type || (type === $sentinel && is_primitive(value))) {
return value;
}
return clone(node);
}
},{"../types/sentinel":137,"./clone":109,"./is-primitive":119}],104:[function(require,module,exports){
var clone_requested = require("./clone-requested-path");
var clone_optimized = require("./clone-optimized-path");
var walk_path_map = require("../walk/walk-path-map-soft-link");
var is_object = require("./is-object");
var empty = [];
module.exports = function(roots, pathmap, keys_stack, depth, requested, optimized) {
var patset_keys = explode_keys(pathmap, keys_stack.concat(), depth);
var pathset = patset_keys.map(function(keys) {
keys = keys.filter(function(key) { return key != "null"; });
switch(keys.length) {
case 0:
return null;
case 1:
return keys[0];
default:
return keys;
}
});
roots.requestedMissingPaths.push(clone_requested(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(clone_optimized(optimized, pathset, depth));
}
function explode_keys(pathmap, keys_stack, depth) {
if(is_object(pathmap)) {
var keys = Object.keys(pathmap);
var keys2 = keys_stack[depth] || (keys_stack[depth] = []);
keys2.push.apply(keys2, keys);
keys.forEach(function(key) {
explode_keys(pathmap[key], keys_stack, depth + 1);
});
}
return keys_stack;
}
},{"../walk/walk-path-map-soft-link":140,"./clone-optimized-path":106,"./clone-requested-path":107,"./is-object":118}],105:[function(require,module,exports){
var clone_requested_path = require("./clone-requested-path");
var clone_optimized_path = require("./clone-optimized-path");
module.exports = function(roots, pathset, depth, requested, optimized) {
roots.requestedMissingPaths.push(clone_requested_path(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(clone_optimized_path(optimized, pathset, depth));
}
},{"./clone-optimized-path":106,"./clone-requested-path":107}],106:[function(require,module,exports){
module.exports = function(optimized, pathset, depth) {
var x;
var i = -1;
var j = depth - 1;
var n = optimized.length;
var m = pathset.length;
var array2 = [];
while(++i < n) {
array2[i] = optimized[i];
}
while(++j < m) {
if((x = pathset[j]) != null) {
array2[i++] = x;
}
}
return array2;
}
},{}],107:[function(require,module,exports){
var is_object = require("./is-object");
module.exports = function(bound, requested, pathset, depth, index) {
var x;
var i = -1;
var j = -1;
var l = 0;
var m = requested.length;
var n = bound.length;
var array2 = [];
while(++i < n) {
array2[i] = bound[i];
}
while(++j < m) {
if((x = requested[j]) != null) {
if(is_object(pathset[l++])) {
array2[i++] = [x];
} else {
array2[i++] = x;
}
}
}
m = n + l + pathset.length - depth;
while(i < m) {
array2[i++] = pathset[l++];
}
if(index != null) {
array2.pathSetIndex = index;
}
return array2;
}
},{"./is-object":118}],108:[function(require,module,exports){
var array_slice = require("./array-slice");
var array_clone = require("./array-clone");
module.exports = function(roots, requested, optimized) {
roots.requestedPaths.push(array_slice(requested, roots.offset));
roots.optimizedPaths.push(array_clone(optimized));
}
},{"./array-clone":100,"./array-slice":101}],109:[function(require,module,exports){
var is_object = require("./is-object");
var prefix = require("../internal/prefix");
module.exports = function(value) {
var dest = value, src = dest, i = -1, n, keys, key;
if(is_object(dest)) {
dest = {};
keys = Object.keys(src);
n = keys.length;
while(++i < n) {
key = keys[i];
if(key[0] !== prefix) {
dest[key] = src[key];
}
}
}
return dest;
}
},{"../internal/prefix":70,"./is-object":118}],110:[function(require,module,exports){
var $path = require("../types/path");
var $expired = "expired";
var replace_node = require("./replace-node");
var graph_node = require("./graph-node");
var update_back_refs = require("./update-back-refs");
var is_primitive = require("./is-primitive");
var is_expired = require("./is-expired");
module.exports = function(roots, parent, node, type, key) {
if(!!type && is_expired(roots, node)) {
type = $expired;
}
if((!!type && type != $path) || is_primitive(node)) {
node = replace_node(parent, node, {}, key, roots.lru);
node = graph_node(roots[0], parent, node, key, 0);
node = update_back_refs(node, roots.version);
}
return node;
}
},{"../types/path":136,"./graph-node":113,"./is-expired":117,"./is-primitive":119,"./replace-node":126,"./update-back-refs":132}],111:[function(require,module,exports){
var __ref = require("../internal/ref");
var __context = require("../internal/context");
var __ref_index = require("../internal/ref-index");
var __refs_length = require("../internal/refs-length");
module.exports = function(node) {
var ref, i = -1, n = node[__refs_length] || 0;
while(++i < n) {
if((ref = node[__ref + i]) !== undefined) {
ref[__context] = ref[__ref_index] = node[__ref + i] = undefined;
}
}
node[__refs_length] = undefined
}
},{"../internal/context":62,"../internal/ref":73,"../internal/ref-index":72,"../internal/refs-length":74}],112:[function(require,module,exports){
module.exports = function(path) {
var key, index = path.length - 1;
do {
if((key = path[index]) != null) {
return key;
}
} while(--index > -1);
return null;
}
},{}],113:[function(require,module,exports){
var __parent = require("../internal/parent");
var __key = require("../internal/key");
var __generation = require("../internal/generation");
module.exports = function(root, parent, node, key, generation) {
node[__parent] = parent;
node[__key] = key;
node[__generation] = generation;
return node;
}
},{"../internal/generation":63,"../internal/key":66,"../internal/parent":69}],114:[function(require,module,exports){
var generation = 0;
module.exports = function() { return generation++; }
},{}],115:[function(require,module,exports){
var version = 0;
module.exports = function() { return version++; }
},{}],116:[function(require,module,exports){
module.exports = invalidate;
var is_object = require("./is-object");
var remove_node = require("./remove-node");
var prefix = require("../internal/prefix");
function invalidate(parent, node, key, lru) {
if(remove_node(parent, node, key, lru)) {
var type = is_object(node) && node.$type || undefined;
if(type == null) {
var keys = Object.keys(node);
for(var i = -1, n = keys.length; ++i < n;) {
var key = keys[i];
if(key[0] !== prefix && key[0] !== "$") {
invalidate(node, node[key], key, lru);
}
}
}
return true;
}
return false;
}
},{"../internal/prefix":70,"./is-object":118,"./remove-node":125}],117:[function(require,module,exports){
var $expires_now = require("../values/expires-now");
var $expires_never = require("../values/expires-never");
var __invalidated = require("../internal/invalidated");
var now = require("./now");
var splice = require("../lru/splice");
module.exports = function(roots, node) {
var expires = node.$expires;
if((expires != null ) && (
expires != $expires_never ) && (
expires == $expires_now || expires < now())) {
if(!node[__invalidated]) {
node[__invalidated] = true;
roots.expired.push(node);
splice(roots.lru, node);
}
return true;
}
return false;
}
},{"../internal/invalidated":65,"../lru/splice":84,"../values/expires-never":138,"../values/expires-now":139,"./now":122}],118:[function(require,module,exports){
var obj_typeof = "object";
module.exports = function(value) {
return value != null && typeof value == obj_typeof;
}
},{}],119:[function(require,module,exports){
var obj_typeof = "object";
module.exports = function(value) {
return value == null || typeof value != obj_typeof;
}
},{}],120:[function(require,module,exports){
module.exports = key_to_keyset;
var __offset = require("../internal/offset");
var is_array = Array.isArray;
var is_object = require("./is-object");
function key_to_keyset(key, iskeyset) {
if(iskeyset) {
if(is_array(key)) {
key = key[key[__offset]];
return key_to_keyset(key, is_object(key));
} else {
return key[__offset];
}
}
return key;
}
},{"../internal/offset":68,"./is-object":118}],121:[function(require,module,exports){
var $self = "./";
var $path = require("../types/path");
var $sentinel = require("../types/sentinel");
var $expires_now = require("../values/expires-now");
var is_object = require("./is-object");
var is_primitive = require("./is-primitive");
var is_expired = require("./is-expired");
var promote = require("../lru/promote");
var wrap_node = require("./wrap-node");
var graph_node = require("./graph-node");
var replace_node = require("../support/replace-node");
var update_graph = require("../support/update-graph");
var inc_generation = require("./inc-generation");
var invalidate_node = require("./invalidate-node");
module.exports = function(roots, parent, node, messageParent, message, key) {
var type, messageType, node_is_object, message_is_object;
// If the cache and message are the same, we can probably return early:
// - If they're both null, return null.
// - If they're both branches, return the branch.
// - If they're both edges, continue below.
if(node == message) {
if(node == null) {
return null;
} else if(node_is_object = is_object(node)) {
type = node.$type;
if(type == null) {
if(node[$self] == null) {
return graph_node(roots[0], parent, node, key, 0);
}
return node;
}
}
} else if(node_is_object = is_object(node)) {
type = node.$type;
}
var value, messageValue;
if(type == $path) {
if(message == null) {
// If the cache is an expired reference, but the message
// is empty, remove the cache value and return undefined
// so we build a missing path.
if(is_expired(roots, node)) {
invalidate_node(parent, node, key, roots.lru);
return undefined;
}
// If the cache has a reference and the message is empty,
// leave the cache alone and follow the reference.
return node;
} else if(message_is_object = is_object(message)) {
messageType = message.$type;
// If the cache and the message are both references,
// check if we need to replace the cache reference.
if(messageType == $path) {
if(node === message) {
// If the cache and message are the same reference,
// we performed a whole-branch merge of one of the
// grandparents. If we've previously graphed this
// reference, break early.
if(node[$self] != null) {
return node;
}
}
// If the message doesn't expire immediately and is newer than the
// cache (or either cache or message don't have timestamps), attempt
// to use the message value.
// Note: Number and `undefined` compared LT/GT to `undefined` is `false`.
else if((
is_expired(roots, message) === false) && ((
message.$timestamp < node.$timestamp) === false)) {
// Compare the cache and message references.
// - If they're the same, break early so we don't insert.
// - If they're different, replace the cache reference.
value = node.value;
messageValue = message.value;
var count = value.length;
// If the reference lengths are equal, check their keys for equality.
if(count === messageValue.length) {
while(--count > -1) {
// If any of their keys are different, replace the reference
// in the cache with the reference in the message.
if(value[count] !== messageValue[count]) {
break;
}
}
// If all their keys are equal, leave the cache value alone.
if(count === -1) {
return node;
}
}
}
}
}
} else {
if(message_is_object = is_object(message)) {
messageType = message.$type;
}
if(node_is_object && !type) {
// Otherwise if the cache is a branch and the message is either
// null or also a branch, continue with the cache branch.
if(message == null || (message_is_object && !messageType)) {
return node;
}
}
}
// If the message is an expired edge, report it back out so we don't build a missing path, but
// don't insert it into the cache. If a value exists in the cache that didn't come from a
// whole-branch grandparent merge, remove the cache value.
if(!!messageType && !!message[$self] && is_expired(roots, message)) {
if(node_is_object && node != message) {
invalidate_node(parent, node, key, roots.lru);
}
return message;
}
// If the cache is a value, but the message is a branch, merge the branch over the value.
else if(!!type && message_is_object && !messageType) {
node = replace_node(parent, node, message, key, roots.lru);
return graph_node(roots[0], parent, node, key, 0);
}
// If the message is a value, insert it into the cache.
else if(!message_is_object || !!messageType) {
var offset = 0;
// If we've arrived at this message value, but didn't perform a whole-branch merge
// on one of its ancestors, replace the cache node with the message value.
if(node != message) {
messageValue || (messageValue = !!messageType ? message.value : message);
message = wrap_node(message, messageType, messageValue);
var size = node_is_object && node.$size || 0;
var messageSize = message.$size;
offset = size - messageSize;
node = replace_node(parent, node, message, key, roots.lru);
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// If the cache and the message are the same value, we branch-merged one of its
// ancestors. Give the message a $size and $type, attach its graph pointers, and
// update the cache sizes and generations.
else if(node_is_object && node[$self] == null) {
node = parent[key] = wrap_node(node, type, node.value);
offset = -node.$size;
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// Otherwise, cache and message are the same primitive value. Wrap in a sentinel and insert.
else {
node = parent[key] = wrap_node(node, type, node);
offset = -node.$size;
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// If the node is already expired, return undefined to build a missing path.
// if(is_expired(roots, node)) {
// return undefined;
// }
// Promote the message edge in the LRU.
promote(roots.lru, node);
}
// If we get here, the cache is empty and the message is a branch.
// Merge the whole branch over.
else if(node == null) {
node = parent[key] = graph_node(roots[0], parent, message, key, 0);
}
return node;
}
},{"../lru/promote":83,"../support/replace-node":126,"../support/update-graph":133,"../types/path":136,"../types/sentinel":137,"../values/expires-now":139,"./graph-node":113,"./inc-generation":114,"./invalidate-node":116,"./is-expired":117,"./is-object":118,"./is-primitive":119,"./wrap-node":134}],122:[function(require,module,exports){
module.exports = Date.now;
},{}],123:[function(require,module,exports){
var inc_version = require("../support/inc-version");
var getBoundValue = require('../get/getBoundValue');
module.exports = function(options, model, error_selector) {
var bound = options.bound || (options.bound = model._path || []);
var root = options.root || (options.root = model._cache);
var nodes = options.nodes || (options.nodes = []);
var lru = options.lru || (options.lru = model._root);
options.expired || (options.expired = lru.expired);
options.errors || (options.errors = []);
options.requestedPaths || (options.requestedPaths = []);
options.optimizedPaths || (options.optimizedPaths = []);
options.requestedMissingPaths || (options.requestedMissingPaths = []);
options.optimizedMissingPaths || (options.optimizedMissingPaths = []);
options.boxed = model._boxed || false;
options.materialized = model._materialized;
options.errorsAsValues = model._treatErrorsAsValues || false;
options.headless = model._dataSource == null;
options.version = inc_version();
options.offset || (options.offset = 0);
options.error_selector = error_selector || model._errorSelector;
if(bound.length) {
nodes[0] = getBoundValue(model, bound).value;
} else {
nodes[0] = root;
}
return options;
};
},{"../get/getBoundValue":45,"../support/inc-version":115}],124:[function(require,module,exports){
module.exports = permute_keyset;
var __offset = require("../internal/offset");
var is_array = Array.isArray;
var is_object = require("./is-object");
function permute_keyset(key) {
if(is_array(key)) {
if(key[__offset] === undefined) {
key[__offset] = -1;
if(key.length == 0) {
return false;
}
}
if(++key[__offset] >= key.length) {
return permute_keyset(key[key[__offset] = -1]);
} else {
return true;
}
} else if(is_object(key)) {
if(key[__offset] === undefined) {
key[__offset] = (key.from || (key.from = 0)) - 1;
if(key.to === undefined) {
if(key.length === undefined) {
throw new Error("Range keysets must specify at least one index to retrieve.");
} else if(key.length === 0) {
return false;
}
key.to = key.from + (key.length || 1) - 1;
}
}
if(++key[__offset] > key.to) {
key[__offset] = key.from - 1;
return false;
}
return true;
}
return false;
}
},{"../internal/offset":68,"./is-object":118}],125:[function(require,module,exports){
var $path = require("../types/path");
var __parent = require("../internal/parent");
var unlink = require("./unlink");
var delete_back_refs = require("./delete-back-refs");
var splice = require("../lru/splice");
var is_object = require("./is-object");
module.exports = function(parent, node, key, lru) {
if(is_object(node)) {
var type = node.$type;
if(!!type) {
if(type == $path) { unlink(node); }
splice(lru, node);
}
delete_back_refs(node);
parent[key] = node[__parent] = undefined;
return true;
}
return false;
}
},{"../internal/parent":69,"../lru/splice":84,"../types/path":136,"./delete-back-refs":111,"./is-object":118,"./unlink":131}],126:[function(require,module,exports){
var transfer_back_refs = require("./transfer-back-refs");
var invalidate_node = require("./invalidate-node");
module.exports = function(parent, node, replacement, key, lru) {
if(node != null && node !== replacement && typeof node == "object") {
transfer_back_refs(node, replacement);
invalidate_node(parent, node, key, lru);
}
return parent[key] = replacement;
}
},{"./invalidate-node":116,"./transfer-back-refs":127}],127:[function(require,module,exports){
var __ref = require("../internal/ref");
var __context = require("../internal/context");
var __refs_length = require("../internal/refs-length");
module.exports = function(node, dest) {
var nodeRefsLength = node[__refs_length] || 0,
destRefsLength = dest[__refs_length] || 0,
i = -1, ref;
while(++i < nodeRefsLength) {
ref = node[__ref + i];
if(ref !== undefined) {
ref[__context] = dest;
dest[__ref + (destRefsLength + i)] = ref;
node[__ref + i] = undefined;
}
}
dest[__refs_length] = nodeRefsLength + destRefsLength;
node[__refs_length] = ref = undefined;
}
},{"../internal/context":62,"../internal/ref":73,"../internal/refs-length":74}],128:[function(require,module,exports){
var $error = require("../types/error");
var promote = require("../lru/promote");
var array_clone = require("./array-clone");
module.exports = function(roots, node, type, path) {
if(node == null) {
return false;
}
promote(roots.lru, node);
if(type != $error || roots.errorsAsValues) {
return false;
}
roots.errors.push({ path: array_clone(path), value: node.value });
return true;
};
},{"../lru/promote":83,"../types/error":135,"./array-clone":100}],129:[function(require,module,exports){
var $sentinel = require("../types/sentinel");
var clone_misses = require("./clone-missing-path-maps");
var is_expired = require("./is-expired");
module.exports = function(roots, node, type, pathmap, keys_stack, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if(node == null && dematerialized) {
clone_misses(roots, pathmap, keys_stack, depth, requested, optimized);
return true;
} else if(!!type) {
if(type == $sentinel && node.value === undefined && dematerialized && !roots.boxed) {
return true;
} else if(is_expired(roots, node)) {
clone_misses(roots, pathmap, keys_stack, depth, requested, optimized);
return true;
}
}
return false;
};
},{"../types/sentinel":137,"./clone-missing-path-maps":104,"./is-expired":117}],130:[function(require,module,exports){
var $sentinel = require("../types/sentinel");
var clone_misses = require("./clone-missing-path-sets");
var is_expired = require("./is-expired");
module.exports = function(roots, node, type, pathset, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if(node == null && dematerialized) {
clone_misses(roots, pathset, depth, requested, optimized);
return true;
} else if(!!type) {
if(type == $sentinel && node.value === undefined && dematerialized && !roots.boxed) {
return true;
} else if(is_expired(roots, node)) {
clone_misses(roots, pathset, depth, requested, optimized);
return true;
}
}
return false;
};
},{"../types/sentinel":137,"./clone-missing-path-sets":105,"./is-expired":117}],131:[function(require,module,exports){
var __ref = require("../internal/ref");
var __context = require("../internal/context");
var __ref_index = require("../internal/ref-index");
var __refs_length = require("../internal/refs-length");
module.exports = function(ref) {
var destination = ref[__context];
if(destination) {
var i = (ref[__ref_index] || 0) - 1,
n = (destination[__refs_length] || 0) - 1;
while(++i <= n) {
destination[__ref + i] = destination[__ref + (i + 1)];
}
destination[__refs_length] = n;
ref[__ref_index] = ref[__context] = destination = undefined;
}
}
},{"../internal/context":62,"../internal/ref":73,"../internal/ref-index":72,"../internal/refs-length":74}],132:[function(require,module,exports){
module.exports = update_back_refs;
var __ref = require("../internal/ref");
var __parent = require("../internal/parent");
var __version = require("../internal/version");
var __generation = require("../internal/generation");
var __refs_length = require("../internal/refs-length");
var generation = require("./inc-generation");
function update_back_refs(node, version) {
if(node && node[__version] !== version) {
node[__version] = version;
node[__generation] = generation();
update_back_refs(node[__parent], version);
var i = -1, n = node[__refs_length] || 0;
while(++i < n) {
update_back_refs(node[__ref + i], version);
}
}
return node;
}
},{"../internal/generation":63,"../internal/parent":69,"../internal/ref":73,"../internal/refs-length":74,"../internal/version":76,"./inc-generation":114}],133:[function(require,module,exports){
var __key = require("../internal/key");
var __version = require("../internal/version");
var __parent = require("../internal/parent");
var remove_node = require("./remove-node");
var update_back_refs = require("./update-back-refs");
module.exports = function(node, offset, version, lru) {
var child;
while(child = node) {
node = child[__parent];
if((child.$size = (child.$size || 0) - offset) <= 0 && node != null) {
remove_node(node, child, child[__key], lru);
} else if(child[__version] !== version) {
update_back_refs(child, version);
}
}
}
},{"../internal/key":66,"../internal/parent":69,"../internal/version":76,"./remove-node":125,"./update-back-refs":132}],134:[function(require,module,exports){
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var now = require("./now");
var clone = require("./clone");
var is_array = Array.isArray;
var is_object = require("./is-object");
module.exports = function(node, type, value) {
var dest = node, size = 0;
if(!!type) {
dest = clone(node);
size = dest.$size;
// }
// if(type == $path) {
// dest = clone(node);
// size = 50 + (value.length || 1);
// } else if(is_object(node) && (type || (type = node.$type))) {
// dest = clone(node);
// size = dest.$size;
} else {
dest = { value: value };
type = $sentinel;
}
if(size <= 0 || size == null) {
switch(typeof value) {
case "number":
case "boolean":
case "function":
case "undefined":
size = 51;
break;
case "object":
size = is_array(value) && (50 + value.length) || 51;
break;
case "string":
size = 50 + value.length;
break;
}
}
var expires = is_object(node) && node.$expires || undefined;
if(typeof expires === "number" && expires < 0) {
dest.$expires = now() + (expires * -1);
}
dest.$type = type;
dest.$size = size;
return dest;
}
},{"../types/error":135,"../types/path":136,"../types/sentinel":137,"./clone":109,"./is-object":118,"./now":122}],135:[function(require,module,exports){
module.exports = "error";
},{}],136:[function(require,module,exports){
module.exports = "ref";
},{}],137:[function(require,module,exports){
module.exports = "sentinel";
},{}],138:[function(require,module,exports){
module.exports = 1;
},{}],139:[function(require,module,exports){
module.exports = 0;
},{}],140:[function(require,module,exports){
module.exports = walk_path_map;
var prefix = require("../internal/prefix");
var $path = require("../types/path");
var walk_reference = require("./walk-reference");
var array_slice = require("../support/array-slice");
var array_clone = require("../support/array-clone");
var array_append = require("../support/array-append");
var is_expired = require("../support/is-expired");
var is_primitive = require("../support/is-primitive");
var is_object = require("../support/is-object");
var is_array = Array.isArray;
var promote = require("../lru/promote");
function walk_path_map(onNode, onEdge, pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(is_primitive(pathmap) || is_primitive(node)) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[0] = parents[0] = roots[0];
nodes[1] = parents[1] = roots[1];
nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
optimized = array_clone(reference);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, true, null, keyset, false);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
if(type != null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keys_stack[depth] = Object.keys(pathmap);
if(keys.length == 0) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var is_outer_keyset = keys.length > 1;
for(var i = -1, n = keys.length; ++i < n;) {
var inner_key = keys[i];
if((inner_key[0] === prefix) || (inner_key[0] === "$")) {
continue;
}
var inner_keyset = is_outer_keyset ? inner_key : keyset;
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var pathmap2 = pathmap[inner_key];
var requested2, optimized2, is_branch;
var has_child_key = false;
var is_branch = is_object(pathmap2) && !pathmap2.$type;// && !is_array(pathmap2);
if(is_branch) {
for(child_key in pathmap2) {
if((child_key[0] === prefix) || (child_key[0] === "$")) {
continue;
}
child_key = pathmap2.hasOwnProperty(child_key);
break;
}
is_branch = child_key === true;
}
if(inner_key == "null") {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
inner_key = key;
inner_keyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
if(is_branch) {
walk_path_map(onNode, onEdge,
pathmap2, keys_stack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
} else {
onEdge(pathmap2, keys_stack, depth, roots, parents2, nodes2, requested2, optimized2, inner_key, inner_keyset);
}
}
}
},{"../internal/prefix":70,"../lru/promote":83,"../support/array-append":99,"../support/array-clone":100,"../support/array-slice":101,"../support/is-expired":117,"../support/is-object":118,"../support/is-primitive":119,"../types/path":136,"./walk-reference":144}],141:[function(require,module,exports){
module.exports = walk_path_map;
var prefix = require("../internal/prefix");
var __context = require("../internal/context");
var $path = require("../types/path");
var walk_reference = require("./walk-reference");
var array_slice = require("../support/array-slice");
var array_clone = require("../support/array-clone");
var array_append = require("../support/array-append");
var is_expired = require("../support/is-expired");
var is_primitive = require("../support/is-primitive");
var is_object = require("../support/is-object");
var is_array = Array.isArray;
var promote = require("../lru/promote");
function walk_path_map(onNode, onEdge, pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(is_primitive(pathmap) || is_primitive(node)) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if(node != null) {
type = node.$type;
optimized = array_clone(reference);
nodes[0] = node;
} else {
nodes[0] = parents[0] = roots[0];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
optimized = array_clone(reference);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, true, null, keyset, false);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
}
if(type != null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keys_stack[depth] = Object.keys(pathmap);
if(keys.length == 0) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var is_outer_keyset = keys.length > 1;
for(var i = -1, n = keys.length; ++i < n;) {
var inner_key = keys[i];
if((inner_key[0] === prefix) || (inner_key[0] === "$")) {
continue;
}
var inner_keyset = is_outer_keyset ? inner_key : keyset;
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var pathmap2 = pathmap[inner_key];
var requested2, optimized2, is_branch;
var child_key = false;
var is_branch = is_object(pathmap2) && !pathmap2.$type;// && !is_array(pathmap2);
if(is_branch) {
for(child_key in pathmap2) {
if((child_key[0] === prefix) || (child_key[0] === "$")) {
continue;
}
child_key = pathmap2.hasOwnProperty(child_key);
break;
}
is_branch = child_key === true;
}
if(inner_key == "null") {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
inner_key = key;
inner_keyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
if(is_branch) {
walk_path_map(onNode, onEdge,
pathmap2, keys_stack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
} else {
onEdge(pathmap2, keys_stack, depth, roots, parents2, nodes2, requested2, optimized2, inner_key, inner_keyset);
}
}
}
},{"../internal/context":62,"../internal/prefix":70,"../lru/promote":83,"../support/array-append":99,"../support/array-clone":100,"../support/array-slice":101,"../support/is-expired":117,"../support/is-object":118,"../support/is-primitive":119,"../types/path":136,"./walk-reference":144}],142:[function(require,module,exports){
module.exports = walk_path_set;
var $path = require("../types/path");
var empty_array = new Array(0);
var walk_reference = require("./walk-reference");
var array_slice = require("../support/array-slice");
var array_clone = require("../support/array-clone");
var array_append = require("../support/array-append");
var is_expired = require("../support/is-expired");
var is_primitive = require("../support/is-primitive");
var is_object = require("../support/is-object");
var keyset_to_key = require("../support/keyset-to-key");
var permute_keyset = require("../support/permute-keyset");
var promote = require("../lru/promote");
function walk_path_set(onNode, onEdge, pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(depth >= pathset.length || is_primitive(node)) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[0] = parents[0] = roots[0];
nodes[1] = parents[1] = roots[1];
nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
optimized = array_clone(reference);
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathset, roots, parents, nodes, requested, optimized, true, false, null, keyset, false);
return onEdge(pathset, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
if(type != null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outer_key = pathset[depth];
var is_outer_keyset = is_object(outer_key);
var is_branch = depth < pathset.length - 1;
var run_once = false;
while(is_outer_keyset && permute_keyset(outer_key) && (run_once = true) || (run_once = !run_once)) {
var inner_key, inner_keyset;
if(is_outer_keyset === true) {
inner_key = keyset_to_key(outer_key, true);
inner_keyset = inner_key;
} else {
inner_key = outer_key;
inner_keyset = keyset;
}
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var requested2, optimized2;
if(inner_key == null) {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
// optimized2 = optimized;
inner_key = key;
inner_keyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
walk_path_set(onNode, onEdge,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
}
}
},{"../lru/promote":83,"../support/array-append":99,"../support/array-clone":100,"../support/array-slice":101,"../support/is-expired":117,"../support/is-object":118,"../support/is-primitive":119,"../support/keyset-to-key":120,"../support/permute-keyset":124,"../types/path":136,"./walk-reference":144}],143:[function(require,module,exports){
module.exports = walk_path_set;
var prefix = require("../internal/prefix");
var __context = require("../internal/context");
var $path = require("../types/path");
var empty_array = new Array(0);
var walk_reference = require("./walk-reference");
var array_slice = require("../support/array-slice");
var array_clone = require("../support/array-clone");
var array_append = require("../support/array-append");
var is_expired = require("../support/is-expired");
var is_primitive = require("../support/is-primitive");
var is_object = require("../support/is-object");
var keyset_to_key = require("../support/keyset-to-key");
var permute_keyset = require("../support/permute-keyset");
var promote = require("../lru/promote");
function walk_path_set(onNode, onEdge, pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(depth >= pathset.length || is_primitive(node)) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if(node != null) {
type = node.$type;
optimized = array_clone(reference);
nodes[0] = node;
} else {
nodes[0] = parents[0] = roots[0];
// nodes[1] = parents[1] = roots[1];
// nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
optimized = array_clone(reference);
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathset, roots, parents, nodes, requested, optimized, true, false, null, keyset, false);
return onEdge(pathset, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
}
if(type != null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outer_key = pathset[depth];
var is_outer_keyset = is_object(outer_key);
var is_branch = depth < pathset.length - 1;
var run_once = false;
while(is_outer_keyset && permute_keyset(outer_key) && (run_once = true) || (run_once = !run_once)) {
var inner_key, inner_keyset;
if(is_outer_keyset === true) {
inner_key = keyset_to_key(outer_key, true);
inner_keyset = inner_key;
} else {
inner_key = outer_key;
inner_keyset = keyset;
}
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var requested2, optimized2;
if(inner_key == null) {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
// optimized2 = optimized;
inner_key = key;
inner_keyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
walk_path_set(onNode, onEdge,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
}
}
},{"../internal/context":62,"../internal/prefix":70,"../lru/promote":83,"../support/array-append":99,"../support/array-clone":100,"../support/array-slice":101,"../support/is-expired":117,"../support/is-object":118,"../support/is-primitive":119,"../support/keyset-to-key":120,"../support/permute-keyset":124,"../types/path":136,"./walk-reference":144}],144:[function(require,module,exports){
module.exports = walk_reference;
var prefix = require("../internal/prefix");
var __ref = require("../internal/ref");
var __context = require("../internal/context");
var __ref_index = require("../internal/ref-index");
var __refs_length = require("../internal/refs-length");
var is_object = require("../support/is-object");
var is_primitive = require("../support/is-primitive");
var array_slice = require("../support/array-slice");
var array_append = require("../support/array-append");
function walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized) {
optimized.length = 0;
var index = -1;
var count = reference.length;
var node, key, keyset;
while(++index < count) {
node = nodes[0];
if(node == null) {
return nodes;
} else if(is_primitive(node) || node.$type) {
onNode(reference, roots, parents, nodes, requested, optimized, false, false, keyset, null, false);
return nodes;
}
do {
key = reference[index];
if(key != null) {
keyset = key;
optimized.push(key);
onNode(reference, roots, parents, nodes, requested, optimized, false, index < count - 1, key, null, false);
break;
}
} while(++index < count);
}
node = nodes[0];
if(is_object(node) && container[__context] !== node) {
var backrefs = node[__refs_length] || 0;
node[__refs_length] = backrefs + 1;
node[__ref + backrefs] = container;
container[__context] = node;
container[__ref_index] = backrefs;
}
return nodes;
}
},{"../internal/context":62,"../internal/prefix":70,"../internal/ref":73,"../internal/ref-index":72,"../internal/refs-length":74,"../support/array-append":99,"../support/array-slice":101,"../support/is-object":118,"../support/is-primitive":119}],145:[function(require,module,exports){
/*global define:false require:false */
module.exports = (function(){
// Import Events
var events = require('events')
// Export Domain
var domain = {}
domain.createDomain = domain.create = function(){
var d = new events.EventEmitter()
function emitError(e) {
d.emit('error', e)
}
d.add = function(emitter){
emitter.on('error', emitError)
}
d.remove = function(emitter){
emitter.removeListener('error', emitError)
}
d.bind = function(fn){
return function(){
var args = Array.prototype.slice.call(arguments)
try {
fn.apply(null, args)
}
catch (err){
emitError(err)
}
}
}
d.intercept = function(fn){
return function(err){
if ( err ) {
emitError(err)
}
else {
var args = Array.prototype.slice.call(arguments, 1)
try {
fn.apply(null, args)
}
catch (err){
emitError(err)
}
}
}
}
d.run = function(fn){
try {
fn()
}
catch (err) {
emitError(err)
}
return this
};
d.dispose = function(){
this.removeAllListeners()
return this
};
d.enter = d.exit = function(){
return this
}
return d
};
return domain
}).call(this)
},{"events":146}],146:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],147:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],148:[function(require,module,exports){
(function (global){
/*!
* Copyright 2014 Netflix, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
!function(e){if("object"==typeof exports)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.falcor=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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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){
module.exports = _dereq_('./operations');
},{"./operations":149}],2:[function(_dereq_,module,exports){
if (typeof falcor === 'undefined') {
var falcor = {};
}
var Rx = _dereq_('./rx.ultralite');
falcor.__Internals = {};
falcor.Observable = Rx.Observable;
falcor.EXPIRES_NOW = 0;
falcor.EXPIRES_NEVER = 1;
/**
* The current semVer'd data version of falcor.
*/
falcor.dataVersion = '0.1.0';
falcor.now = function now() {
return Date.now();
};
falcor.NOOP = function() {};
module.exports = falcor;
},{"./rx.ultralite":41}],3:[function(_dereq_,module,exports){
var falcor = _dereq_('./Falcor');
var RequestQueue = _dereq_('./request/RequestQueue');
var ImmediateScheduler = _dereq_('./scheduler/ImmediateScheduler');
var TimeoutScheduler = _dereq_('./scheduler/TimeoutScheduler');
var ERROR = _dereq_("../types/error");
var ModelResponse = _dereq_('./ModelResponse');
var call = _dereq_('./operations/call');
var operations = _dereq_('./operations');
var dotSyntaxParser = _dereq_('./operations/parser/parser');
var getBoundValue = _dereq_('./../get/getBoundValue');
var slice = Array.prototype.slice;
var $ref = _dereq_('./../types/path');
var $error = _dereq_('./../types/error');
var $sentinel = _dereq_('./../types/sentinel');
var Model = module.exports = falcor.Model = function Model(options) {
if (!options) {
options = {};
}
this._materialized = options.materialized || false;
this._boxed = options.boxed || false;
this._treatErrorsAsValues = options.treatErrorsAsValues || false;
this._dataSource = options.source;
this._maxSize = options.maxSize || Math.pow(2, 53) - 1;
this._collectRatio = options.collectRatio || 0.75;
this._scheduler = new ImmediateScheduler();
this._request = new RequestQueue(this, this._scheduler);
this._errorSelector = options.errorSelector || Model.prototype._errorSelector;
this._router = options.router;
this._root = options.root || {
expired: [],
allowSync: false,
unsafeMode: true
};
if (options.cache && typeof options.cache === "object") {
this.setCache(options.cache);
} else {
this._cache = {};
}
this._path = [];
};
Model.EXPIRES_NOW = falcor.EXPIRES_NOW;
Model.EXPIRES_NEVER = falcor.EXPIRES_NEVER;
Model.ref = function(path) {
if (typeof path === 'string') {
path = dotSyntaxParser(path);
}
return {$type: $ref, value: path};
};
Model.error = function(error) {
return {$type: $error, value: error};
};
Model.atom = function(value) {
return {$type: $sentinel, value: value};
};
Model.prototype = {
_boxed: false,
_progressive: false,
_errorSelector: function(x, y) { return y; },
get: operations('get'),
set: operations("set"),
invalidate: operations("invalidate"),
call: call,
getValue: function(path) {
return this.get(path, function(x) { return x });
},
setValue: function(path, value) {
return this.set(Array.isArray(path) ?
{path: path, value: value} :
path, function(x) { return x; });
},
bind: function(boundPath) {
var model = this, root = model._root,
paths = new Array(arguments.length - 1),
i = -1, n = arguments.length - 1;
while(++i < n) {
paths[i] = arguments[i + 1];
}
if(n === 0) { throw new Error("Model#bind requires at least one value path."); }
return falcor.Observable.create(function(observer) {
var boundModel;
try {
root.allowSync = true;
if(!(boundModel = model.bindSync(model._path.concat(boundPath)))) {
throw false;
}
root.allowSync = false;
observer.onNext(boundModel);
observer.onCompleted();
} catch (e) {
root.allowSync = false;
return model.get.apply(model, paths.map(function(path) {
return boundPath.concat(path);
}).concat(function(){})).subscribe(
function onNext() {},
function onError(err) { observer.onError(err); },
function onCompleted() {
try {
if(boundModel = model.bindSync(boundPath)) {
observer.onNext(boundModel);
}
observer.onCompleted();
} catch(e) {
observer.onError(e);
}
});
}
});
},
setCache: function(cache) {
return (this._cache = {}) && this._setCache(this, cache);
},
getValueSync: function(path) {
if (Array.isArray(path) === false) {
throw new Error("Model#getValueSync must be called with an Array path.");
}
if (this._path.length) {
path = this._path.concat(path);
}
return this.syncCheck("getValueSync") && this._getValueSync(this, path).value;
},
setValueSync: function(path, value, errorSelector) {
if(Array.isArray(path) === false) {
if(typeof errorSelector !== "function") {
errorSelector = value || this._errorSelector;
}
value = path.value;
path = path.path;
}
if(Array.isArray(path) === false) {
throw new Error("Model#setValueSync must be called with an Array path.");
}
if(this.syncCheck("setValueSync")) {
var json = {};
var tEeAV = this._treatErrorsAsValues;
var boxed = this._boxed;
this._treatErrorsAsValues = true;
this._boxed = true;
this._setPathSetsAsJSON(this, [{path: path, value: value}], [json], errorSelector);
this._treatErrorsAsValues = tEeAV;
this._boxed = boxed;
json = json.json;
if(json && json.$type === ERROR && !this._treatErrorsAsValues) {
if(this._boxed) {
throw json;
} else {
throw json.value;
}
} else if(this._boxed) {
return json;
}
return json && json.value;
}
},
bindSync: function(path) {
if(Array.isArray(path) === false) {
throw new Error("Model#bindSync must be called with an Array path.");
}
var boundValue = this.syncCheck("bindSync") && getBoundValue(this, this._path.concat(path));
var node = boundValue.value;
path = boundValue.path;
if(boundValue.shorted) {
if(!!node) {
if(node.$type === ERROR) {
if(this._boxed) {
throw node;
}
throw node.value;
// throw new Error("Model#bindSync can\'t bind to or beyond an error: " + boundValue.toString());
}
}
return undefined;
} else if(!!node && node.$type === ERROR) {
if(this._boxed) {
throw node;
}
throw node.value;
}
return this.clone(["_path", boundValue.path]);
},
// TODO: This seems like a great place for optimizations
clone: function() {
var self = this;
var clone = new Model();
Object.keys(self).forEach(function(key) {
clone[key] = self[key];
});
slice.call(arguments).forEach(function(tuple) {
clone[tuple[0]] = tuple[1];
});
return clone;
},
batch: function(schedulerOrDelay) {
if(typeof schedulerOrDelay === "number") {
schedulerOrDelay = new TimeoutScheduler(Math.round(Math.abs(schedulerOrDelay)));
} else if(!schedulerOrDelay || !schedulerOrDelay.schedule) {
schedulerOrDelay = new ImmediateScheduler();
}
return this.clone(["_request", new RequestQueue(this, schedulerOrDelay)]);
},
unbatch: function() {
return this.clone(["_request", new RequestQueue(this, new ImmediateScheduler())]);
},
treatErrorsAsValues: function() {
return this.clone(["_treatErrorsAsValues", true]);
},
materialize: function() {
return this.clone(["_materialized", true]);
},
boxValues: function() {
return this.clone(["_boxed", true]);
},
unboxValues: function() {
return this.clone(["_boxed", false]);
},
withoutDataSource: function() {
return this.clone(["_dataSource", null]);
},
syncCheck: function(name) {
if (!!this._dataSource && this._root.allowSync === false && this._root.unsafeMode === false) {
throw new Error("Model#" + name + " may only be called within the context of a request selector.");
}
return true;
}
};
},{"../types/error":139,"./../get/getBoundValue":49,"./../types/error":139,"./../types/path":140,"./../types/sentinel":141,"./Falcor":2,"./ModelResponse":4,"./operations":11,"./operations/call":6,"./operations/parser/parser":16,"./request/RequestQueue":40,"./scheduler/ImmediateScheduler":42,"./scheduler/TimeoutScheduler":43}],4:[function(_dereq_,module,exports){
var falcor = _dereq_('./Falcor');
var Observable = falcor.Observable,
valuesMixin = { format: { value: "AsValues" } },
jsonMixin = { format: { value: "AsPathMap" } },
jsongMixin = { format: { value: "AsJSONG" } },
progressiveMixin = { operationIsProgressive: { value: true } };
function ModelResponse(forEach) {
this._subscribe = forEach;
}
ModelResponse.create = function(forEach) {
return new ModelResponse(forEach);
};
ModelResponse.fromOperation = function(model, args, selector, forEach) {
return new ModelResponse(function(observer) {
return forEach(Object.create(observer, {
operationModel: {value: model},
operationArgs: {value: args},
operationSelector: {value: selector}
}));
});
};
function noop() {}
function mixin(self) {
var mixins = Array.prototype.slice.call(arguments, 1);
return new ModelResponse(function(other) {
return self.subscribe(mixins.reduce(function(proto, mixin) {
return Object.create(proto, mixin);
}, other));
});
}
ModelResponse.prototype = Observable.create(noop);
ModelResponse.prototype.format = "AsPathMap";
ModelResponse.prototype.toPathValues = function() {
return mixin(this, valuesMixin);
};
ModelResponse.prototype.toJSON = function() {
return mixin(this, jsonMixin);
};
ModelResponse.prototype.progressively = function() {
return mixin(this, progressiveMixin);
};
ModelResponse.prototype.toJSONG = function() {
return mixin(this, jsongMixin);
};
module.exports = ModelResponse;
},{"./Falcor":2}],5:[function(_dereq_,module,exports){
var falcor = _dereq_('./Falcor');
var Model = _dereq_('./Model');
falcor.Model = Model;
module.exports = falcor;
},{"./Falcor":2,"./Model":3}],6:[function(_dereq_,module,exports){
module.exports = call;
var falcor = _dereq_("../../Falcor");
var ModelResponse = _dereq_('./../../ModelResponse');
function call(path, args, suffixes, paths, selector) {
var model = this;
args && Array.isArray(args) || (args = []);
suffixes && Array.isArray(suffixes) || (suffixes = []);
paths = Array.prototype.slice.call(arguments, 3);
if (typeof (selector = paths[paths.length - 1]) !== "function") {
selector = undefined;
} else {
paths = paths.slice(0, -1);
}
return ModelResponse.create(function (options) {
var rootModel = model.clone(["_path", []]),
localRoot = rootModel.withoutDataSource(),
dataSource = model._dataSource,
boundPath = model._path,
callPath = boundPath.concat(path),
thisPath = callPath.slice(0, -1);
var disposable = model.
getValue(path).
flatMap(function (localFn) {
if (typeof localFn === "function") {
return falcor.Observable.return(localFn.
apply(rootModel.bindSync(thisPath), args).
map(function (pathValue) {
return {
path: thisPath.concat(pathValue.path),
value: pathValue.value
};
}).
toArray().
flatMap(function (pathValues) {
return localRoot.set.
apply(localRoot, pathValues).
toJSONG();
}).
flatMap(function (envelope) {
return rootModel.get.apply(rootModel,
envelope.paths.reduce(function (paths, path) {
return paths.concat(suffixes.map(function (suffix) {
return path.concat(suffix);
}));
}, []).
concat(paths.reduce(function (paths, path) {
return paths.concat(thisPath.concat(path));
}, []))).
toJSONG();
}));
}
return falcor.Observable.empty();
}).
defaultIfEmpty(dataSource.call(path, args, suffixes, paths)).
mergeAll().
subscribe(function (envelope) {
var invalidated = envelope.invalidated;
if (invalidated && invalidated.length) {
invalidatePaths(rootModel, invalidated, undefined, model._errorSelector);
}
disposable = localRoot.
set(envelope, function () {
return model;
}).
subscribe(function (model) {
var getPaths = envelope.paths.map(function (path) {
return path.slice(boundPath.length);
});
if (selector) {
getPaths[getPaths.length] = function () {
return selector.call(model, getPaths);
};
}
disposable = model.get.apply(model, getPaths).subscribe(options);
});
});
return {
dispose: function () {
disposable && disposable.dispose();
disposable = undefined;
}
};
});
}
},{"../../Falcor":2,"./../../ModelResponse":4}],7:[function(_dereq_,module,exports){
var combineOperations = _dereq_('./../support/combineOperations');
var setSeedsOrOnNext = _dereq_('./../support/setSeedsOrOnNext');
/**
* The initial args that are passed into the async request pipeline.
* @see lib/falcor/operations/request.js for how initialArgs are used
*/
module.exports = function getInitialArgs(options, seeds, onNext) {
var seedRequired = options.format !== 'AsValues';
var isProgressive = options.operationIsProgressive;
var spreadOperations = false;
var operations =
combineOperations(
options.operationArgs, options.format, 'get',
spreadOperations, isProgressive);
setSeedsOrOnNext(
operations, seedRequired, seeds, onNext, options.operationSelector);
var requestOptions;
return [operations];
};
},{"./../support/combineOperations":26,"./../support/setSeedsOrOnNext":39}],8:[function(_dereq_,module,exports){
var getSourceObserver = _dereq_('./../support/getSourceObserever');
var partitionOperations = _dereq_('./../support/partitionOperations');
var mergeBoundPath = _dereq_('./../support/mergeBoundPath');
module.exports = getSourceRequest;
function getSourceRequest(
options, onNext, seeds, combinedResults, requestOptions, cb) {
var model = options.operationModel;
var boundPath = model._path;
var missingPaths = combinedResults.requestedMissingPaths;
if (boundPath.length) {
for (var i = 0; i < missingPaths.length; ++i) {
var pathSetIndex = missingPaths[i].pathSetIndex;
var path = missingPaths[i] = boundPath.concat(missingPaths[i]);
path.pathSetIndex = pathSetIndex;
}
}
return model._request.get(
missingPaths,
combinedResults.optimizedMissingPaths,
getSourceObserver(
model,
missingPaths,
function getSourceCallback(err, results) {
if (err) {
cb(err);
return;
}
// partitions the operations by their pathSetIndex
var partitionOperationsAndSeeds = partitionOperations(
results,
seeds,
options.format,
onNext);
// We allow for the rerequesting to happen.
cb(null, partitionOperationsAndSeeds);
}));
}
},{"./../support/getSourceObserever":27,"./../support/mergeBoundPath":31,"./../support/partitionOperations":34}],9:[function(_dereq_,module,exports){
var getInitialArgs = _dereq_('./getInitialArgs');
var getSourceRequest = _dereq_('./getSourceRequest');
var shouldRequest = _dereq_('./shouldRequest');
var request = _dereq_('./../request');
var processOperations = _dereq_('./../support/processOperations');
var get = request(
getInitialArgs,
getSourceRequest,
processOperations,
shouldRequest);
module.exports = get;
},{"./../request":18,"./../support/processOperations":36,"./getInitialArgs":7,"./getSourceRequest":8,"./shouldRequest":10}],10:[function(_dereq_,module,exports){
module.exports = function(model, combinedResults) {
return model._dataSource && combinedResults.requestedMissingPaths.length > 0;
};
},{}],11:[function(_dereq_,module,exports){
var ModelResponse = _dereq_('../ModelResponse');
var get = _dereq_('./get');
var set = _dereq_('./set');
var invalidate = _dereq_('./invalidate');
module.exports = function modelOperation(name) {
return function() {
var model = this, root = model._root,
args = Array.prototype.slice.call(arguments),
selector = args[args.length - 1];
if (typeof selector === 'function') {
args.pop();
} else {
selector = false;
}
var modelResponder;
switch (name) {
case 'get':
modelResponder = get;
break;
case 'set':
modelResponder = set;
break;
case 'invalidate':
modelResponder = invalidate;
break;
}
return ModelResponse.fromOperation(
model,
args,
selector,
modelResponder);
};
};
},{"../ModelResponse":4,"./get":9,"./invalidate":12,"./set":19}],12:[function(_dereq_,module,exports){
var invalidateInitialArgs = _dereq_('./invalidateInitialArgs');
var request = _dereq_('./../request');
var processOperations = _dereq_('./../support/processOperations');
var invalidate = request(
invalidateInitialArgs,
null,
processOperations);
module.exports = invalidate;
},{"./../request":18,"./../support/processOperations":36,"./invalidateInitialArgs":13}],13:[function(_dereq_,module,exports){
var combineOperations = _dereq_('./../support/combineOperations');
var setSeedsOrOnNext = _dereq_('./../support/setSeedsOrOnNext');
module.exports = function getInitialArgs(options, seeds, onNext) {
var seedRequired = options.format !== 'AsValues';
var operations = combineOperations(
options.operationArgs, options.format, 'inv');
setSeedsOrOnNext(
operations, seedRequired, seeds,
onNext, options.operationSelector);
return [operations, seeds];
};
},{"./../support/combineOperations":26,"./../support/setSeedsOrOnNext":39}],14:[function(_dereq_,module,exports){
module.exports = {
token: 'token',
dotSeparator: '.',
commaSeparator: ',',
openingBracket: '[',
closingBracket: ']',
space: 'space',
quote: 'quote',
unknown: 'unknown'
};
},{}],15:[function(_dereq_,module,exports){
module.exports = {
nestedIndexers: 'Indexers cannot be nested',
closingWithoutOpeningIndexer: 'A closing indexer, "]", was provided without an opening indexer.',
leadingDotInIndexer: 'The dot operator in an indexer cannot be used this way.',
twoDot: 'Cannot have two dot separators outside of an indexer range.',
dotComma: 'Cannot have a comma preceded by a dot separator.',
commasOutsideOfIndexers: 'Commas cannot be used outside of indexers.',
trailingComma: 'Cannot have trailing commas in indexers.',
leadingComma: 'Leading commas in ranges are not allowed.',
emptyQuotes: 'Cannot have empty quotes',
emptyIndexer: 'Cannot have empty indexer.',
quotesOutsideIndexer: 'Cannot have quotes outside indexer.',
nonTerminatingQuotes: 'The quotes within the indexer were not closed.',
tokensMustBeNumeric: 'Tokens without quotes must be numeric.',
indexerTokensMustBeCommaDelimited: 'Indexer tokens must be comma delimited.',
numericRange: 'Only numeric keys can be used in ranges.'
};
},{}],16:[function(_dereq_,module,exports){
var tokenizer = _dereq_('./tokenizer');
var TokenTypes = _dereq_('./TokenTypes');
var Expections = _dereq_('./expections');
/**
* not only is this the parser, it is also the
* semantic analyzer for brevity sake / we never need
* this to change overall types of output.
*/
module.exports = function parser(string) {
var out = [];
var tokenized = tokenizer(string);
var state = {};
var token = tokenized();
while (!token.done) {
switch (token.type) {
case TokenTypes.token:
insertToken(token.token, state, out);
break;
case TokenTypes.dotSeparator:
dotSeparator(token.token, state, out);
break;
case TokenTypes.space:
space(token.token, state, out);
break;
case TokenTypes.commaSeparator:
commaSeparator(token.token, state, out);
break;
case TokenTypes.openingBracket:
openIndexer(token.token, state, out);
break;
case TokenTypes.closingBracket:
closeIndexer(token.token, state, out);
break;
case TokenTypes.quote:
quote(token.token, state, out);
break;
}
token = tokenized();
}
return out;
};
function space(token, state, out) {
// The space character only matters when inIndexer
// and in quote mode.
if (state.inIndexer && state.quote) {
state.indexerToken += token;
}
}
function insertToken(token, state, out) {
state.hasDot = false;
// if within indexer then there are several edge cases.
if (state.inIndexer) {
tokenInIndexer(token, state, out);
return;
}
// if not in indexer just insert into end position.
out[out.length] = token;
}
function dotSeparator(token, state, out) {
// If in indexer then dotOperators have different meanings.
if (state.inIndexer) {
indexerDotOperator(token, state, out);
}
// throws an expection if a range operator is outside of a range.
else if (state.hasDot) {
throw Expections.twoDot;
}
state.hasDot = true;
}
function commaSeparator(token, state, out) {
if (state.hasDot) {
throw Expections.dotComma;
}
// If in indexer then dotOperators have different meanings.
if (state.inIndexer) {
indexerCommaOperator(token, state, out);
}
}
// Accumulates dotSeparators inside indexers
function indexerDotOperator(token, state, out) {
// must be preceded by token.
if (state.indexerToken === undefined) {
throw Expections.leadingDotInIndexer;
}
// if in quote mode, add the dot indexer to quote.
if (state.quote) {
state.indexerToken += token;
return;
}
if (!state.rangeCount) {
state.range = true;
state.rangeCount = 0;
}
++state.rangeCount;
if (state.rangeCount === 2) {
state.inclusiveRange = true;
}
else if (state.rangeCount === 3) {
state.exclusiveRange = true;
state.inclusiveRange = false;
}
}
function indexerCommaOperator(token, state, out) {
// are we a range indexer?
if (state.range) {
closeRangedIndexer(token, state, out);
}
// push previous token and clear state.
else if (state.inIndexer) {
pushTokenIntoIndexer(token, state, out);
}
// If a comma is used outside of an indexer throw
else {
throw Expections.commasOutsideOfIndexers;
}
}
function pushTokenIntoIndexer(token, state, out) {
// no token to push, throw error.
if (state.indexerToken === undefined) {
throw Expections.leadingComma;
}
// push the current token onto the stack then clear state.
state.indexer[state.indexer.length] = state.indexerToken;
cleanIndexerTokenState(state);
}
function openIndexer(token, state, out) {
if (state.inIndexer) {
throw Expections.nestedIndexers;
}
state.inIndexer = true;
state.indexer = [];
}
function closeIndexer(token, state, out) {
// must be within an indexer to close.
if (!state.inIndexer) {
throw Expections.closingWithoutOpeningIndexer;
}
// The quotes could be non terminating
if (state.quote) {
throw Expections.nonTerminatingQuotes;
}
// are we a range indexer?
if (state.range) {
closeRangedIndexer(token, state, out);
}
// are we have a token?
else if (state.indexerToken !== undefined) {
pushTokenIntoIndexer(token, state, out);
}
// empty indexer. Must be after the potential addition
// statements.
if (state.indexer && state.indexer.length === 0) {
throw Expections.emptyIndexer;
}
// flatten to avoid odd JSON output.
if (state.indexer && state.indexer.length === 1) {
state.indexer = state.indexer[0];
}
out[out.length] = state.indexer;
// removes all indexer state
cleanIndexerRangeState(state);
cleanIndexerTokenState(state);
state.indexer =
state.inIndexer = undefined;
}
function closeRangedIndexer(token, state, out) {
state.indexer[state.indexer.length] = {
from: state.indexerToken,
to: state.rangeCloseToken - (state.exclusiveRange && 1 || 0)
};
cleanIndexerRangeState(state);
}
function cleanIndexerRangeState(state) {
state.inclusiveRange =
state.exclusiveRange =
state.range =
state.rangeCloseToken =
state.rangeCount = undefined;
}
// removes state associated with indexerTokenState.
function cleanIndexerTokenState(state) {
state.indexerToken =
state.indexerTokenQuoted = undefined;
}
function tokenInRange(token, state, out) {
token = +token;
if (isNaN(token)) {
throw Expections.numericRange;
}
state.rangeCloseToken = token;
}
function tokenInIndexer(token, state, out) {
// finish the range token.
if (state.range) {
tokenInRange(token, state, out);
}
// quote mode, accumulate tokens.
else if (state.quote) {
if (state.indexerToken === undefined) {
state.indexerToken = '';
}
state.indexerToken += token;
}
// We are in range mode.
else {
token = +token;
if (isNaN(token)) {
throw Expections.tokensMustBeNumeric;
}
state.indexerToken = token;
}
}
// this function just ensures that quotes only happen in indexers,
// outside of ranges, and with 1 or more length tokens.
function quote(token, state, out) {
if (state.indexerTokenQuoted) {
throw Expections.indexerTokensMustBeCommaDelimited;
}
if (!state.inIndexer) {
throw Expections.quotesOutsideIndexer;
}
var was = state.quote;
var toBe = !was;
state.quote = toBe;
// so deep
if (was && !toBe) {
if (state.indexerToken === undefined) {
throw Expections.emptyQuotes;
}
state.indexerTokenQuoted = true;
}
}
},{"./TokenTypes":14,"./expections":15,"./tokenizer":17}],17:[function(_dereq_,module,exports){
var TokenTypes = _dereq_('./TokenTypes');
var DOT_SEPARATOR = '.';
var COMMA_SEPARATOR = ',';
var OPENING_BRACKET = '[';
var CLOSING_BRACKET = ']';
var DOUBLE_OUOTES = '"';
var SINGE_OUOTES = "'";
var SPACE = " ";
var SPECIAL_CHARACTERS = '\'"[]., ';
var TokenTypes = _dereq_('./TokenTypes');
module.exports = function tokenizer(string) {
var idx = -1;
return function() {
var token = '';
var done;
do {
done = idx === string.length;
if (done) {
return {done: true};
}
// we have to peek at the next token
var character = string[idx + 1];
// if its not a special character we need to accumulate it.
var isQuote = character === SINGE_OUOTES ||
character === DOUBLE_OUOTES;
if (character !== undefined &&
SPECIAL_CHARACTERS.indexOf(character) === -1) {
token += character;
++idx;
continue;
}
if (token.length) {
return toOutput(token, TokenTypes.token, done);
}
++idx;
var type;
switch (character) {
case DOT_SEPARATOR:
type = TokenTypes.dotSeparator;
break;
case COMMA_SEPARATOR:
type = TokenTypes.commaSeparator;
break;
case OPENING_BRACKET:
type = TokenTypes.openingBracket;
break;
case CLOSING_BRACKET:
type = TokenTypes.closingBracket;
break;
case SPACE:
type = TokenTypes.space;
break;
case DOUBLE_OUOTES:
case SINGE_OUOTES:
type = TokenTypes.quote;
break;
}
if (type) {
return toOutput(token, type, done);
}
} while (!done);
if (token.length) {
return toOutput(token, TokenTypes.token, false);
}
return {done: true};
};
};
function toOutput(token, type, done) {
return {
token: token,
done: done,
type: type
};
}
},{"./TokenTypes":14}],18:[function(_dereq_,module,exports){
var setSeedsOrOnNext = _dereq_('./support/setSeedsOrOnNext');
var onNextValues = _dereq_('./support/onNextValue');
var onCompletedOrError = _dereq_('./support/onCompletedOrError');
var dotSyntaxParser = _dereq_('./parser/parser');
var primeSeeds = _dereq_('./support/primeSeeds');
var autoFalse = function() { return false; };
module.exports = request;
function request(initialArgs, sourceRequest, processOperations, shouldRequestFn) {
if (!shouldRequestFn) {
shouldRequestFn = autoFalse;
}
return function innerRequest(options) {
var selector = options.operationSelector;
var model = options.operationModel;
var args = options.operationArgs;
var onNext = options.onNext.bind(options);
var onError = options.onError.bind(options);
var onCompleted = options.onCompleted.bind(options);
var isProgressive = options.operationIsProgressive;
var errorSelector = model._errorSelector;
var selectorLength = selector && selector.length || 0;
// State variables
var errors = [];
var format = options.format = selector && 'AsJSON' ||
options.format || 'AsPathMap';
var toJSONG = format === 'AsJSONG';
var toJSON = format === 'AsPathMap';
var toPathValues = format === 'AsValues';
var seedRequired = toJSON || toJSONG || selector;
var boundPath = model._path;
var i, len;
var foundValue = false;
var seeds = primeSeeds(selector, selectorLength);
var loopCount = 0;
// parse any dotSyntax
for (i = 0, len = args.length; i < len; i++) {
// it is a dotSyntax string.
if (typeof args[i] === 'string') {
args[i] = dotSyntaxParser(args[i]);
}
// it is a pathValue with dotSyntax.
else if (typeof args[i].path === 'string') {
args[i].path = dotSyntaxParser(args[i].path);
}
}
function recurse(operations, opts) {
if (loopCount > 50) {
throw 'Loop Kill switch thrown.';
}
var combinedResults = processOperations(
model,
operations,
errorSelector,
opts);
foundValue = foundValue || combinedResults.valuesReceived;
if (combinedResults.errors.length) {
errors = errors.concat(combinedResults.errors);
}
// if in progressiveMode, values are emitted
// each time through the recurse loop. This may have
// to change when the router is considered.
if (isProgressive && !toPathValues) {
onNextValues(model, onNext, seeds, selector);
}
// Performs the recursing via dataSource
if (shouldRequestFn(model, combinedResults, loopCount)) {
sourceRequest(
options,
onNext,
seeds,
combinedResults,
opts,
function onCompleteFromSourceSet(err, results) {
if (err) {
errors = errors.concat(err);
recurse([], seeds);
return;
}
++loopCount;
// We continue to string the opts through
recurse(results, opts);
});
}
// Else we need to onNext values and complete/error.
else {
if (!toPathValues && !isProgressive && foundValue) {
onNextValues(model, onNext, seeds, selector);
}
onCompletedOrError(onCompleted, onError, errors);
}
}
try {
recurse.apply(null,
initialArgs(options, seeds, onNext));
} catch(e) {
errors = [e];
onCompletedOrError(onCompleted, onError, errors);
}
};
}
},{"./parser/parser":16,"./support/onCompletedOrError":32,"./support/onNextValue":33,"./support/primeSeeds":35,"./support/setSeedsOrOnNext":39}],19:[function(_dereq_,module,exports){
var setInitialArgs = _dereq_('./setInitialArgs');
var setSourceRequest = _dereq_('./setSourceRequest');
var request = _dereq_('./../request');
var setProcessOperations = _dereq_('./setProcessOperations');
var shouldRequest = _dereq_('./shouldRequest');
var set = request(
setInitialArgs,
setSourceRequest,
setProcessOperations,
shouldRequest);
module.exports = set;
},{"./../request":18,"./setInitialArgs":20,"./setProcessOperations":21,"./setSourceRequest":22,"./shouldRequest":23}],20:[function(_dereq_,module,exports){
var combineOperations = _dereq_('./../support/combineOperations');
var setSeedsOrOnNext = _dereq_('./../support/setSeedsOrOnNext');
var Formats = _dereq_('./../support/Formats');
var toPathValues = Formats.toPathValues;
var toJSONG = Formats.toJSONG;
module.exports = function setInitialArgs(options, seeds, onNext) {
var isPathValues = options.format === toPathValues;
var seedRequired = !isPathValues;
var shouldRequest = !!options.operationModel._dataSource;
var format = options.format;
var args = options.operationArgs;
var selector = options.operationSelector;
var isProgressive = options.operationIsProgressive;
var firstSeeds, operations;
var requestOptions = {
removeBoundPath: shouldRequest
};
// If Model is a slave, in shouldRequest mode,
// a single seed is required to accumulate the jsong results.
if (shouldRequest) {
operations =
combineOperations(args, toJSONG, 'set', selector, false);
firstSeeds = [{}];
setSeedsOrOnNext(
operations, true, firstSeeds, false, options.selector);
// we must keep track of the set seeds.
requestOptions.requestSeed = firstSeeds[0];
}
// This model is the master, therefore a regular set can be performed.
else {
firstSeeds = seeds;
operations = combineOperations(args, format, 'set');
setSeedsOrOnNext(
operations, seedRequired, seeds, onNext, options.operationSelector);
}
// We either have to construct the master operations if
// the ModelResponse is isProgressive
// the ModelResponse is toPathValues
// but luckily we can just perform a get for the progressive or
// toPathValues mode.
if (isProgressive || isPathValues) {
var getOps = combineOperations(
args, format, 'get', selector, true);
setSeedsOrOnNext(
getOps, seedRequired, seeds, onNext, options.operationSelector);
operations = operations.concat(getOps);
requestOptions.isProgressive = true;
}
return [operations, requestOptions];
};
},{"./../support/Formats":24,"./../support/combineOperations":26,"./../support/setSeedsOrOnNext":39}],21:[function(_dereq_,module,exports){
var processOperations = _dereq_('./../support/processOperations');
var combineOperations = _dereq_('./../support/combineOperations');
var mergeBoundPath = _dereq_('./../support/mergeBoundPath');
var Formats = _dereq_('./../support/Formats');
var toPathValues = Formats.toPathValues;
module.exports = setProcessOperations;
function setProcessOperations(model, operations, errorSelector, requestOptions) {
var boundPath = model._path;
var hasBoundPath = boundPath.length > 0;
var removeBoundPath = requestOptions && requestOptions.removeBoundPath;
var isProgressive = requestOptions && requestOptions.isProgressive;
var progressiveOperations;
// if in progressive mode, then the progressive operations
// need to be executed but the bound path must stay intact.
if (isProgressive && removeBoundPath && hasBoundPath) {
progressiveOperations = operations.filter(function(op) {
return op.isProgressive;
});
operations = operations.filter(function(op) {
return !op.isProgressive;
});
}
if (removeBoundPath && hasBoundPath) {
model._path = [];
// For every operations arguments, the bound path must be adjusted.
for (var i = 0, opLen = operations.length; i < opLen; i++) {
var args = operations[i].args;
for (var j = 0, argsLen = args.length; j < argsLen; j++) {
args[j] = mergeBoundPath(args[j], boundPath);
}
}
}
var results = processOperations(model, operations, errorSelector);
// Undo what we have done to the model's bound path.
if (removeBoundPath && hasBoundPath) {
model._path = boundPath;
}
// executes the progressive ops
if (progressiveOperations) {
processOperations(model, progressiveOperations, errorSelector);
}
return results;
}
},{"./../support/Formats":24,"./../support/combineOperations":26,"./../support/mergeBoundPath":31,"./../support/processOperations":36}],22:[function(_dereq_,module,exports){
var getSourceObserver = _dereq_('./../support/getSourceObserever');
var combineOperations = _dereq_('./../support/combineOperations');
var setSeedsOrOnNext = _dereq_('./../support/setSeedsOrOnNext');
var toPathValues = _dereq_('./../support/Formats').toPathValues;
module.exports = setSourceRequest;
function setSourceRequest(
options, onNext, seeds, combinedResults, requestOptions, cb) {
var model = options.operationModel;
var seedRequired = options.format !== toPathValues;
var requestSeed = requestOptions.requestSeed;
return model._request.set(
requestSeed,
getSourceObserver(
model,
requestSeed.paths,
function setSourceRequestCB(err, results) {
if (err) {
cb(err);
}
// Sets the results into the model.
model._setJSONGsAsJSON(model, [results], []);
// Gets the original paths / maps back out.
var operations = combineOperations(
options.operationArgs, options.format, 'get');
setSeedsOrOnNext(
operations, seedRequired,
seeds, onNext, options.operationSelector);
// unset the removeBoundPath.
requestOptions.removeBoundPath = false;
cb(null, operations);
}));
}
},{"./../support/Formats":24,"./../support/combineOperations":26,"./../support/getSourceObserever":27,"./../support/setSeedsOrOnNext":39}],23:[function(_dereq_,module,exports){
// Set differs from get in the sense that the first time through
// the recurse loop a server operation must be performed if it can be.
module.exports = function(model, combinedResults, loopCount) {
return model._dataSource && (
combinedResults.requestedMissingPaths.length > 0 ||
loopCount === 0);
};
},{}],24:[function(_dereq_,module,exports){
module.exports = {
toPathValues: 'AsValues',
toJSON: 'AsPathMap',
toJSONG: 'AsJSONG',
selector: 'AsJSON',
};
},{}],25:[function(_dereq_,module,exports){
module.exports = function buildJSONGOperation(format, seeds, jsongOp, seedOffset, onNext) {
return {
methodName: '_setJSONGs' + format,
format: format,
isValues: format === 'AsValues',
onNext: onNext,
seeds: seeds,
seedsOffset: seedOffset,
args: [jsongOp]
};
};
},{}],26:[function(_dereq_,module,exports){
var isSeedRequired = _dereq_('./seedRequired');
var isJSONG = _dereq_('./isJSONG');
var isPathOrPathValue = _dereq_('./isPathOrPathValue');
var Formats = _dereq_('./Formats');
var toSelector = Formats.selector;
module.exports = function combineOperations(args, format, name, spread, isProgressive) {
var seedRequired = isSeedRequired(format);
var isValues = !seedRequired;
var hasSelector = seedRequired && format === toSelector;
var seedsOffset = 0;
return args.
reduce(function(groups, argument) {
var group = groups[groups.length - 1];
var type = isPathOrPathValue(argument) ? "PathSets" :
isJSONG(argument) ? "JSONGs" : "PathMaps";
var groupType = group && group.type;
var methodName = '_' + name + type + format;
if (!groupType || type !== groupType || spread) {
group = {
methodName: methodName,
format: format,
operation: name,
isValues: isValues,
seeds: [],
onNext: null,
seedsOffset: seedsOffset,
isProgressive: isProgressive,
type: type,
args: []
};
groups.push(group);
}
if (hasSelector) {
++seedsOffset;
}
group.args.push(argument);
return groups;
}, []);
};
},{"./Formats":24,"./isJSONG":29,"./isPathOrPathValue":30,"./seedRequired":37}],27:[function(_dereq_,module,exports){
var insertErrors = _dereq_('./insertErrors.js');
/**
* creates the model source observer
* @param {Model} model
* @param {Array.<Array>} requestedMissingPaths
* @param {Function} cb
*/
function getSourceObserver(model, requestedMissingPaths, cb) {
var incomingValues;
return {
onNext: function(jsongEnvelop) {
incomingValues = {
jsong: jsongEnvelop.jsong,
paths: requestedMissingPaths
};
},
onError: function(err) {
cb(insertErrors(model, requestedMissingPaths, err));
},
onCompleted: function() {
cb(false, incomingValues);
}
};
}
module.exports = getSourceObserver;
},{"./insertErrors.js":28}],28:[function(_dereq_,module,exports){
/**
* will insert the error provided for every requestedPath.
* @param {Model} model
* @param {Array.<Array>} requestedPaths
* @param {Object} err
*/
module.exports = function insertErrors(model, requestedPaths, err) {
var out = model._setPathSetsAsJSON.apply(null, [model].concat(
requestedPaths.
reduce(function(acc, r) {
acc[0].push({
path: r,
value: err
});
return acc;
}, [[]]),
[],
model._errorSelector
));
return out.errors;
};
},{}],29:[function(_dereq_,module,exports){
module.exports = function isJSONG(x) {
return x.hasOwnProperty("jsong");
};
},{}],30:[function(_dereq_,module,exports){
module.exports = function isPathOrPathValue(x) {
return !!(Array.isArray(x)) || (
x.hasOwnProperty("path") && x.hasOwnProperty("value"));
};
},{}],31:[function(_dereq_,module,exports){
var isJSONG = _dereq_('./isJSONG');
var isPathValue = _dereq_('./isPathOrPathValue');
module.exports = mergeBoundPath;
function mergeBoundPath(arg, boundPath) {
return isJSONG(arg) && mergeBoundPathIntoJSONG(arg, boundPath) ||
isPathValue(arg) && mergeBoundPathIntoPathValue(arg, boundPath) ||
mergeBoundPathIntoJSON(arg, boundPath);
}
function mergeBoundPathIntoJSONG(jsongEnv, boundPath) {
var newJSONGEnv = {jsong: jsongEnv.jsong, paths: jsongEnv.paths};
if (boundPath.length) {
var paths = [];
for (i = 0, len = jsongEnv.paths.length; i < len; i++) {
paths[i] = boundPath.concat(jsongEnv.paths[i]);
}
newJSONGEnv.paths = paths;
}
return newJSONGEnv;
}
function mergeBoundPathIntoJSON(arg, boundPath) {
var newArg = arg;
if (boundPath.length) {
newArg = {};
for (var i = 0, len = boundPath.length - 1; i < len; i++) {
newArg[boundPath[i]] = {};
}
newArg[boundPath[i]] = arg;
}
return newArg;
}
function mergeBoundPathIntoPathValue(arg, boundPath) {
return {
path: boundPath.concat(arg.path),
value: arg.value
};
}
},{"./isJSONG":29,"./isPathOrPathValue":30}],32:[function(_dereq_,module,exports){
module.exports = function onCompletedOrError(onCompleted, onError, errors) {
if (errors.length) {
onError(errors);
} else {
onCompleted();
}
};
},{}],33:[function(_dereq_,module,exports){
/**
* will onNext the observer with the seeds provided.
* @param {Model} model
* @param {Function} onNext
* @param {Array.<Object>} seeds
* @param {Function} [selector]
*/
module.exports = function onNextValues(model, onNext, seeds, selector) {
var root = model._root;
root.allowSync = true;
if (selector) {
if (seeds.length) {
// they should be wrapped in json items
onNext(selector.apply(model, seeds.map(function(x, i) {
return x.json;
})));
} else {
onNext(selector.call(model));
}
} else {
// this means there is an onNext function that is not AsValues or progressive,
// therefore there must only be one onNext call, which should only be the 0
// index of the values of the array
onNext(seeds[0]);
}
root.allowSync = false;
};
},{}],34:[function(_dereq_,module,exports){
var buildJSONGOperation = _dereq_('./buildJSONGOperation');
/**
* It performs the opposite of combine operations. It will take a JSONG
* response and partition them into the required amount of operations.
* @param {{jsong: {}, paths:[]}} jsongResponse
*/
module.exports = partitionOperations;
function partitionOperations(
jsongResponse, seeds, format, onNext) {
var partitionedOps = [];
var requestedMissingPaths = jsongResponse.paths;
if (format === 'AsJSON') {
// fast collapse ass the requestedMissingPaths into their
// respective groups
var opsFromRequestedMissingPaths = [];
var op = null;
for (var i = 0, len = requestedMissingPaths.length; i < len; i++) {
var missingPath = requestedMissingPaths[i];
if (!op || op.idx !== missingPath.pathSetIndex) {
op = {
idx: missingPath.pathSetIndex,
paths: []
};
opsFromRequestedMissingPaths.push(op);
}
op.paths.push(missingPath);
}
opsFromRequestedMissingPaths.forEach(function(op, i) {
var seed = [seeds[op.idx]];
var jsong = {
jsong: jsongResponse.jsong,
paths: op.paths
};
partitionedOps.push(buildJSONGOperation(
format,
seed,
jsong,
op.idx,
onNext));
});
} else {
partitionedOps[0] = buildJSONGOperation(format, seeds, jsongResponse, 0, onNext);
}
return partitionedOps;
}
},{"./buildJSONGOperation":25}],35:[function(_dereq_,module,exports){
module.exports = function primeSeeds(selector, selectorLength) {
var seeds = [];
if (selector) {
for (i = 0; i < selectorLength; i++) {
seeds.push({});
}
} else {
seeds[0] = {};
}
return seeds;
};
},{}],36:[function(_dereq_,module,exports){
module.exports = function processOperations(model, operations, errorSelector, boundPath) {
return operations.reduce(function(memo, operation) {
var jsonGraphOperation = model[operation.methodName];
var seedsOrFunction = operation.isValues ?
operation.onNext : operation.seeds;
var results = jsonGraphOperation(
model,
operation.args,
seedsOrFunction,
operation.onNext,
errorSelector,
boundPath);
var missing = results.requestedMissingPaths;
var offset = operation.seedsOffset;
for (var i = 0, len = missing.length; i < len; i++) {
missing[i].boundPath = boundPath;
missing[i].pathSetIndex += offset;
}
memo.requestedMissingPaths = memo.requestedMissingPaths.concat(missing);
memo.optimizedMissingPaths = memo.optimizedMissingPaths.concat(results.optimizedMissingPaths);
memo.errors = memo.errors.concat(results.errors);
memo.valuesReceived = memo.valuesReceived || results.requestedPaths.length > 0;
return memo;
}, {
errors: [],
requestedMissingPaths: [],
optimizedMissingPaths: [],
valuesReceived: false
});
}
},{}],37:[function(_dereq_,module,exports){
module.exports = function isSeedRequired(format) {
return format === 'AsJSON' || format === 'AsJSONG' || format === 'AsPathMap';
};
},{}],38:[function(_dereq_,module,exports){
module.exports = function setSeedsOnGroups(groups, seeds, hasSelector) {
var valueIndex = 0;
var seedsLength = seeds.length;
var j, i, len = groups.length, gLen, group;
if (hasSelector) {
for (i = 0; i < len && valueIndex < seedsLength; i++) {
group = groups[i];
gLen = gLen = group.args.length;
for (j = 0; j < gLen && valueIndex < seedsLength; j++, valueIndex++) {
group.seeds.push(seeds[valueIndex]);
}
}
} else {
for (i = 0; i < len && valueIndex < seedsLength; i++) {
groups[i].seeds = seeds;
}
}
}
},{}],39:[function(_dereq_,module,exports){
var setSeedsOnGroups = _dereq_('./setSeedsOnGroups');
module.exports = function setSeedsOrOnNext(operations, seedRequired, seeds, onNext, selector) {
if (seedRequired) {
setSeedsOnGroups(operations, seeds, selector);
} else {
for (i = 0; i < operations.length; i++) {
operations[i].onNext = onNext;
}
}
};
},{"./setSeedsOnGroups":38}],40:[function(_dereq_,module,exports){
var falcor = _dereq_('./../Falcor');
var NOOP = falcor.NOOP;
var RequestQueue = function(jsongModel, scheduler) {
this._scheduler = scheduler;
this._jsongModel = jsongModel;
this._scheduled = false;
this._requests = [];
};
RequestQueue.prototype = {
_get: function() {
var i = -1;
var requests = this._requests;
while (++i < requests.length) {
if (!requests[i].pending && requests[i].isGet) {
return requests[i];
}
}
return requests[requests.length] = new GetRequest(this._jsongModel, this);
},
_set: function() {
var i = -1;
var requests = this._requests;
// TODO: Set always sends off a request immediately, so there is no batching.
while (++i < requests.length) {
if (!requests[i].pending && requests[i].isSet) {
return requests[i];
}
}
return requests[requests.length] = new SetRequest(this._jsongModel, this);
},
remove: function(request) {
for (var i = this._requests.length - 1; i > -1; i--) {
if (this._requests[i].id === request.id && this._requests.splice(i, 1)) {
break;
}
}
},
set: function(jsongEnv, observer) {
var self = this;
var disposable = self._set().batch(jsongEnv, observer).flush();
return {
dispose: function() {
disposable.dispose();
}
};
},
get: function(requestedPaths, optimizedPaths, observer) {
var self = this;
var disposable = null;
// TODO: get does not batch across requests.
self._get().batch(requestedPaths, optimizedPaths, observer);
if (!self._scheduled) {
self._scheduled = true;
disposable = self._scheduler.schedule(self._flush.bind(self));
}
return {
dispose: function() {
disposable.dispose();
}
};
},
_flush: function() {
this._scheduled = false;
var requests = this._requests, i = -1;
var disposables = [];
while (++i < requests.length) {
if (!requests[i].pending) {
disposables[disposables.length] = requests[i].flush();
}
}
return {
dispose: function() {
disposables.forEach(function(d) { d.dispose(); });
}
};
}
};
var REQUEST_ID = 0;
var SetRequest = function(model, queue) {
var self = this;
self._jsongModel = model;
self._queue = queue;
self.observers = [];
self.jsongEnvs = [];
self.pending = false;
self.id = ++REQUEST_ID;
self.isSet = true;
};
SetRequest.prototype = {
batch: function(jsongEnv, observer) {
var self = this;
observer.onNext = observer.onNext || NOOP;
observer.onError = observer.onError || NOOP;
observer.onCompleted = observer.onCompleted || NOOP;
if (!observer.__observerId) {
observer.__observerId = ++REQUEST_ID;
}
observer._requestId = self.id;
self.observers[self.observers.length] = observer;
self.jsongEnvs[self.jsongEnvs.length] = jsongEnv;
return self;
},
flush: function() {
var incomingValues, query, op, len;
var self = this;
var jsongs = self.jsongEnvs;
var observers = self.observers;
var model = self._jsongModel;
self.pending = true;
// TODO: Set does not batch.
return model._dataSource.
set(jsongs[0]).
subscribe(function(response) {
incomingValues = response;
}, function(err) {
var i = -1;
var n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onError && obs.onError(err);
}
}, function() {
var i, n, obs;
self._queue.remove(self);
i = -1;
n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onNext && obs.onNext({
jsong: incomingValues.jsong || incomingValues.value,
paths: incomingValues.paths
});
obs.onCompleted && obs.onCompleted();
}
});
}
};
var GetRequest = function(jsongModel, queue) {
var self = this;
self._jsongModel = jsongModel;
self._queue = queue;
self.observers = [];
self.optimizedPaths = [];
self.requestedPaths = [];
self.pending = false;
self.id = ++REQUEST_ID;
self.isGet = true;
};
GetRequest.prototype = {
batch: function(requestedPaths, optimizedPaths, observer) {
// TODO: Do we need to gap fill?
var self = this;
observer.onNext = observer.onNext || NOOP;
observer.onError = observer.onError || NOOP;
observer.onCompleted = observer.onCompleted || NOOP;
if (!observer.__observerId) {
observer.__observerId = ++REQUEST_ID;
}
observer._requestId = self.id;
self.observers[self.observers.length] = observer;
self.optimizedPaths[self.optimizedPaths.length] = optimizedPaths;
self.requestedPaths[self.requestedPaths.length] = requestedPaths;
return self;
},
flush: function() {
var incomingValues, query, op, len;
var self = this;
var requested = self.requestedPaths;
var optimized = self.optimizedPaths;
var observers = self.observers;
var disposables = [];
var results = [];
var model = self._jsongModel;
self._scheduled = false;
self.pending = true;
var optimizedMaps = {};
var requestedMaps = {};
var r, o, i, j, obs, resultIndex;
for (i = 0, len = requested.length; i < len; i++) {
r = requested[i];
o = optimized[i];
obs = observers[i];
for (j = 0; j < r.length; j++) {
pathsToMapWithObservers(r[j], 0, readyNode(requestedMaps, null, obs), obs);
pathsToMapWithObservers(o[j], 0, readyNode(optimizedMaps, null, obs), obs);
}
}
return model._dataSource.
get(collapse(optimizedMaps)).
subscribe(function(response) {
incomingValues = response;
}, function(err) {
var i = -1;
var n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onError && obs.onError(err);
}
}, function() {
var i, n, obs;
self._queue.remove(self);
i = -1;
n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onNext && obs.onNext({
jsong: incomingValues.jsong || incomingValues.value,
paths: incomingValues.paths
});
obs.onCompleted && obs.onCompleted();
}
});
},
// Returns the paths that are contained within this request.
contains: function(requestedPaths, optimizedPaths) {
// TODO:
}
};
function pathsToMapWithObservers(path, idx, branch, observer) {
var curr = path[idx];
// Object / Array
if (typeof curr === 'object') {
if (Array.isArray(curr)) {
curr.forEach(function(v) {
readyNode(branch, v, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[v], observer);
}
});
} else {
var from = curr.from || 0;
var to = curr.to >= 0 ? curr.to : curr.length;
for (var i = from; i <= to; i++) {
readyNode(branch, i, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[i], observer);
}
}
}
} else {
readyNode(branch, curr, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[curr], observer);
}
}
}
/**
* Builds the set of collapsed
* queries by traversing the tree
* once
*/
var charPattern = /\D/i;
function readyNode(branch, key, observer) {
if (key === null) {
branch.__observers = branch.__observers || [];
!containsObserver(branch.__observers, observer) && branch.__observers.push(observer);
return branch;
}
if (!branch[key]) {
branch[key] = {__observers: []};
}
!containsObserver(branch[key].__observers, observer) && branch[key].__observers.push(observer);
return branch;
}
function containsObserver(observers, observer) {
if (!observer) {
return;
}
return observers.reduce(function(acc, x) {
return acc || x.__observerId === observer.__observerId;
}, false);
}
function collapse(pathMap) {
return rangeCollapse(buildQueries(pathMap));
}
/**
* Collapse ranges, e.g. when there is a continuous range
* in an array, turn it into an object instead
*
* [1,2,3,4,5,6] => {"from":1, "to":6}
*
*/
function rangeCollapse(paths) {
paths.forEach(function (path) {
path.forEach(function (elt, index) {
var range;
if (Array.isArray(elt) && elt.every(isNumber) && allUnique(elt)) {
elt.sort(function(a, b) {
return a - b;
});
if (elt[elt.length-1] - elt[0] === elt.length-1) {
// create range
range = {};
range.from = elt[0];
range.to = elt[elt.length-1];
path[index] = range;
}
}
});
});
return paths;
}
/* jshint forin: false */
function buildQueries(root) {
if (root == null || typeof root !== 'object') {
return [ [] ];
}
var children = Object.keys(root).filter(notPathMapInternalKeys),
child, memo, paths, key, childIsNum,
list, head, tail, clone, results,
i = -1, n = children.length,
j, k, x;
if (n === 0 || Array.isArray(root) === true) {
return [ [] ];
}
memo = {};
while(++i < n) {
child = children[i];
paths = buildQueries(root[child]);
key = createKey(paths);
childIsNum = typeof child === 'string' && !charPattern.test(child);
if ((list = memo[key]) && (head = list.head)) {
head[head.length] = childIsNum ? parseInt(child, 10) : child;
} else {
memo[key] = {
head: [childIsNum ? parseInt(child, 10) : child],
tail: paths
};
}
}
results = [];
for(x in memo) {
head = (list = memo[x]).head;
tail = list.tail;
i = -1;
n = tail.length;
while(++i < n) {
list = tail[i];
j = -1;
k = list.length;
if(head[0] === '') {
clone = [];
} else {
clone = [head.length === 1 ? head[0] : head];
while(++j < k) {
clone[j + 1] = list[j];
}
}
results[results.length] = clone;
}
}
return results;
}
function notPathMapInternalKeys(key) {
return (
key !== "__observers" &&
key !== "__pending" &&
key !== "__batchID"
);
}
/**
* Return true if argument is a number
*/
function isNumber(val) {
return typeof val === "number";
}
/**
* allUnique
* return true if every number in an array is unique
*/
function allUnique(arr) {
var hash = {},
index,
len;
for (index = 0, len = arr.length; index < len; index++) {
if (hash[arr[index]]) {
return false;
}
hash[arr[index]] = true;
}
return true;
}
/**
* Sort a list-of-lists
* Used for generating a unique hash
* key for each subtree; used by the
* memoization
*/
function sortLol(lol) {
return lol.reduce(function (result, curr) {
if (curr instanceof Array) {
result.push(sortLol(curr).slice(0).sort());
return result;
}
return result.concat(curr);
}, []).slice(0).sort();
}
/**
* Create a unique hash key for a set
* of paths
*/
function createKey(list) {
return JSON.stringify(sortLol(list));
}
// Note: For testing
falcor.__Internals.buildQueries = buildQueries;
module.exports = RequestQueue;
},{"./../Falcor":2}],41:[function(_dereq_,module,exports){
(function (global){
/**
Rx Ultralite!
Rx on the Roku Tyler throws this (possibly related to browserify-ing Rx):
Error: 'TypeError: 'undefined' is not a function (evaluating 'root.document.createElement('script')')'
*/
var Rx;
if (typeof window !== "undefined" && typeof window["Rx"] !== "undefined") {
// Browser environment
Rx = window["Rx"];
} else if (typeof global !== "undefined" && typeof global["Rx"] !== "undefined") {
// Node.js environment
Rx = global["Rx"];
} else if (typeof _dereq_ !== 'undefined' || typeof window !== 'undefined' && window.require) {
var r = typeof _dereq_ !== 'undefined' && _dereq_ || window.require;
try {
// CommonJS environment with rx module
Rx = r("rx");
} catch(e) {
Rx = undefined;
}
}
if(Rx === undefined) {
Rx = {
I: function() { return arguments[0]; },
Disposable: (function() {
function Disposable(a) {
this.action = a;
}
Disposable.create = function(a) {
return new Disposable(a);
};
Disposable.empty = new Disposable(function(){});
Disposable.prototype.dispose = function() {
if(typeof this.action === 'function') {
this.action();
}
};
return Disposable;
})(),
Observable: (function() {
function Observable(s) {
this._subscribe = s;
}
Observable.create = Observable.createWithDisposable = function(s) {
return new Observable(s);
};
Observable.fastCreateWithDisposable = Observable.create;
Observable.fastReturnValue = function(value) {
return Observable.create(function(observer) {
observer.onNext(value);
observer.onCompleted();
});
};
// NOTE: Required for Router
Observable.prototype.from;
Observable.prototype.materialize;
Observable.prototype.reduce;
Observable.of = function() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return Observable.create(function(observer) {
var errorOcurred = false;
try {
for(var i = 0; i < len; ++i) {
observer.onNext(args[i]);
}
} catch(e) {
errorOcurred = true;
observer.onError(e);
}
if(errorOcurred !== true) {
observer.onCompleted();
}
});
}
Observable.prototype.subscribe = function(n, e, c) {
return this._subscribe(
(n != null && typeof n === 'object') ?
n :
Rx.Observer.create(n, e, c)
);
};
Observable.prototype.forEach = Observable.prototype.subscribe;
Observable.prototype.catchException = function(next) {
var self = this;
return Observable.create(function(o) {
return self.subscribe(
function(x) { o.onNext(x); },
function(e) {
return (
(typeof next === 'function') ?
next(e) : next
).subscribe(o);
},
function() { o.onCompleted(); });
});
};
return Observable;
})(),
Observer: (function() {
function Observer(n, e, c) {
this.onNext = n || Rx.I;
this.onError = e || Rx.I;
this.onCompleted = c || Rx.I;
}
Observer.create = function(n, e, c) {
return new Observer(n, e, c);
};
return Observer;
})(),
Subject: (function(){
function Subject() {
this.observers = [];
}
Subject.prototype.subscribe = function(subscriber) {
var a = this.observers,
n = a.length;
a[n] = subscriber;
return {
dispose: function() {
a.splice(n, 1);
}
}
};
Subject.prototype.onNext = function(x) {
var listeners = this.observers.concat(),
i = -1, n = listeners.length;
while(++i < n) {
listeners[i].onNext(x);
}
};
Subject.prototype.onError = function(e) {
var listeners = this.observers.concat(),
i = -1, n = listeners.length;
this.observers.length = 0;
while(++i < n) {
listeners[i].onError(e);
}
};
Subject.prototype.onCompleted = function() {
var listeners = this.observers.concat(),
i = -1, n = listeners.length;
this.observers.length = 0;
while(++i < n) {
listeners[i].onCompleted();
}
};
})()
};
}
module.exports = Rx;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],42:[function(_dereq_,module,exports){
function ImmediateScheduler() {
}
ImmediateScheduler.prototype = {
schedule: function(action) {
action();
}
};
module.exports = ImmediateScheduler;
},{}],43:[function(_dereq_,module,exports){
function TimeoutScheduler(delay) {
this.delay = delay;
}
TimeoutScheduler.prototype = {
schedule: function(action) {
setTimeout(action, this.delay);
}
};
module.exports = TimeoutScheduler;
},{}],44:[function(_dereq_,module,exports){
var hardLink = _dereq_('./util/hardlink');
var createHardlink = hardLink.create;
var onValue = _dereq_('./onValue');
var isExpired = _dereq_('./util/isExpired');
var $path = _dereq_('./../types/path.js');
var __context = _dereq_("../internal/context");
function followReference(model, root, node, referenceContainer, reference, seed, outputFormat) {
var depth = 0;
var k, next;
while (true) {
if (depth === 0 && referenceContainer[__context]) {
depth = reference.length;
next = referenceContainer[__context];
} else {
k = reference[depth++];
next = node[k];
}
if (next) {
var type = next.$type;
var value = type && next.value || next;
if (depth < reference.length) {
if (type) {
node = next;
break;
}
node = next;
continue;
}
// We need to report a value or follow another reference.
else {
node = next;
if (type && isExpired(next)) {
break;
}
if (!referenceContainer[__context]) {
createHardlink(referenceContainer, next);
}
// Restart the reference follower.
if (type === $path) {
if (outputFormat === 'JSONG') {
onValue(model, next, seed, null, null, reference, null, outputFormat);
}
depth = 0;
reference = value;
referenceContainer = next;
node = root;
continue;
}
break;
}
} else {
node = undefined;
}
break;
}
if (depth < reference.length) {
var ref = [];
for (var i = 0; i < depth; i++) {
ref[i] = reference[i];
}
reference = ref;
}
return [node, reference];
}
module.exports = followReference;
},{"../internal/context":66,"./../types/path.js":140,"./onValue":56,"./util/hardlink":58,"./util/isExpired":59}],45:[function(_dereq_,module,exports){
var getBoundValue = _dereq_('./getBoundValue');
var isPathValue = _dereq_('./util/isPathValue');
module.exports = function(walk) {
return function getAsJSON(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var requestedMissingPaths = results.requestedMissingPaths;
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var missingIdx = 0;
var boundOptimizedPath, optimizedPath;
var i, j, len, bLen;
results.values = values;
if (!values) {
values = [];
}
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (i = 0, len = paths.length; i < len; i++) {
var valueNode = undefined;
var pathSet = paths[i];
if (values[i]) {
valueNode = values[i];
}
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[i] = boundOptimizedPath[i];
}
}
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, 'JSON');
if (missingIdx < requestedMissingPaths.length) {
for (j = missingIdx, length = requestedMissingPaths.length; j < length; j++) {
requestedMissingPaths[j].pathSetIndex = i;
}
missingIdx = length;
}
}
return results;
};
};
},{"./getBoundValue":49,"./util/isPathValue":61}],46:[function(_dereq_,module,exports){
var getBoundValue = _dereq_('./getBoundValue');
var isPathValue = _dereq_('./util/isPathValue');
module.exports = function(walk) {
return function getAsJSONG(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
results.values = values;
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
if (boundPath.length) {
throw 'It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.';
} else {
currentCachePosition = cache;
}
for (var i = 0, len = paths.length; i < len; i++) {
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, values[0], [], results, [], [], inputFormat, 'JSONG');
}
return results;
};
};
},{"./getBoundValue":49,"./util/isPathValue":61}],47:[function(_dereq_,module,exports){
var getBoundValue = _dereq_('./getBoundValue');
var isPathValue = _dereq_('./util/isPathValue');
module.exports = function(walk) {
return function getAsPathMap(model, paths, values) {
var valueNode;
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
valueNode = values[0];
results.values = values;
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[i] = boundOptimizedPath[i];
}
}
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, 'PathMap');
}
return results;
};
};
},{"./getBoundValue":49,"./util/isPathValue":61}],48:[function(_dereq_,module,exports){
var getBoundValue = _dereq_('./getBoundValue');
var isPathValue = _dereq_('./util/isPathValue');
module.exports = function(walk) {
return function getAsValues(model, paths, onNext) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[i] = boundOptimizedPath[i];
}
}
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, onNext, null, results, optimizedPath, [], inputFormat, 'Values');
}
return results;
};
};
},{"./getBoundValue":49,"./util/isPathValue":61}],49:[function(_dereq_,module,exports){
var getValueSync = _dereq_('./getValueSync');
module.exports = function getBoundValue(model, path) {
var boxed, value, shorted;
boxed = model._boxed;
model._boxed = true;
value = getValueSync(model, path.concat(null));
model._boxed = boxed;
path = value.optimizedPath;
shorted = value.shorted;
value = value.value;
while (path.length && path[path.length - 1] === null) {
path.pop();
}
return {
path: path,
value: value,
shorted: shorted
};
};
},{"./getValueSync":50}],50:[function(_dereq_,module,exports){
var followReference = _dereq_('./followReference');
var clone = _dereq_('./util/clone');
var isExpired = _dereq_('./util/isExpired');
var promote = _dereq_('./util/lru').promote;
var $path = _dereq_('./../types/path.js');
var $sentinel = _dereq_('./../types/sentinel.js');
var $error = _dereq_('./../types/error.js');
module.exports = function getValueSync(model, simplePath) {
var root = model._cache;
var len = simplePath.length;
var optimizedPath = [];
var shorted = false, shouldShort = false;
var depth = 0;
var key, next = root, type, curr = root, out, ref, refNode;
do {
key = simplePath[depth++];
if (key !== null) {
next = curr[key];
}
if (!next) {
out = undefined;
shorted = true;
break;
}
type = next.$type;
optimizedPath.push(key);
// Up to the last key we follow references
if (depth < len) {
if (type === $path) {
ref = followReference(model, root, root, next, next.value);
refNode = ref[0];
if (!refNode) {
out = undefined;
break;
}
type = refNode.$type;
next = refNode;
optimizedPath = ref[1];
}
if (type) {
break;
}
}
// If there is a value, then we have great success, else, report an undefined.
else {
out = next;
}
curr = next;
} while (next && depth < len);
if (depth < len) {
// Unfortunately, if all that follows are nulls, then we have not shorted.
for (;depth < len; ++depth) {
if (simplePath[depth] !== null) {
shouldShort = true;
break;
}
}
// if we should short or report value. Values are reported on nulls.
if (shouldShort) {
shorted = true;
out = undefined;
} else {
out = next;
}
}
// promotes if not expired
if (out) {
if (isExpired(out)) {
out = undefined;
} else {
promote(model, out);
}
}
if (out && out.$type === $error && !model._treatErrorsAsValues) {
throw {path: simplePath, value: out.value};
} else if (out && model._boxed) {
out = !!type ? clone(out) : out;
} else if (!out && model._materialized) {
out = {$type: $sentinel};
} else if (out) {
out = out.value;
}
return {
value: out,
shorted: shorted,
optimizedPath: optimizedPath
};
};
},{"./../types/error.js":139,"./../types/path.js":140,"./../types/sentinel.js":141,"./followReference":44,"./util/clone":57,"./util/isExpired":59,"./util/lru":62}],51:[function(_dereq_,module,exports){
var followReference = _dereq_('./followReference');
var onError = _dereq_('./onError');
var onMissing = _dereq_('./onMissing');
var onValue = _dereq_('./onValue');
var lru = _dereq_('./util/lru');
var hardLink = _dereq_('./util/hardlink');
var isMaterialized = _dereq_('./util/isMaterialzed');
var removeHardlink = hardLink.remove;
var splice = lru.splice;
var isExpired = _dereq_('./util/isExpired');
var permuteKey = _dereq_('./util/permuteKey');
var $path = _dereq_('./../types/path');
var $error = _dereq_('./../types/error');
var __invalidated = _dereq_("../internal/invalidated");
// TODO: Objectify?
function walk(model, root, curr, pathOrJSON, depth, seedOrFunction, positionalInfo, outerResults, optimizedPath, requestedPath, inputFormat, outputFormat, fromReference) {
if ((!curr || curr && curr.$type) &&
evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference)) {
return;
}
// We continue the search to the end of the path/json structure.
else {
// Base case of the searching: Have we hit the end of the road?
// Paths
// 1) depth === path.length
// PathMaps (json input)
// 2) if its an object with no keys
// 3) its a non-object
var jsonQuery = inputFormat === 'JSON';
var atEndOfJSONQuery = false;
var k, i, len;
if (jsonQuery) {
// it has a $type property means we have hit a end.
if (pathOrJSON && pathOrJSON.$type) {
atEndOfJSONQuery = true;
}
// is it an object?
else if (pathOrJSON && typeof pathOrJSON === 'object') {
// A terminating condition
k = Object.keys(pathOrJSON);
if (k.length === 1) {
k = k[0];
}
}
// found a primitive, we hit the end.
else {
atEndOfJSONQuery = true;
}
} else {
k = pathOrJSON[depth];
}
// BaseCase: we have hit the end of our query without finding a 'leaf' node, therefore emit missing.
if (atEndOfJSONQuery || !jsonQuery && depth === pathOrJSON.length) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
return;
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
return;
}
var memo = {done: false};
var permutePosition = positionalInfo;
var permuteRequested = requestedPath;
var permuteOptimized = optimizedPath;
var asJSONG = outputFormat === 'JSONG';
var asJSON = outputFormat === 'JSON';
var isKeySet = false;
var hasChildren = false;
depth++;
var key;
if (k && typeof k === 'object') {
memo.isArray = Array.isArray(k);
memo.arrOffset = 0;
key = permuteKey(k, memo);
isKeySet = true;
} else {
key = k;
memo.done = true;
}
if (asJSON && isKeySet) {
permutePosition = [];
for (i = 0, len = positionalInfo.length; i < len; i++) {
permutePosition[i] = positionalInfo[i];
}
permutePosition.push(depth - 1);
}
do {
fromReference = false;
if (!memo.done) {
permuteOptimized = [];
permuteRequested = [];
for (i = 0, len = requestedPath.length; i < len; i++) {
permuteRequested[i] = requestedPath[i];
}
for (i = 0, len = optimizedPath.length; i < len; i++) {
permuteOptimized[i] = optimizedPath[i];
}
}
var nextPathOrPathMap = jsonQuery ? pathOrJSON[key] : pathOrJSON;
if (jsonQuery && nextPathOrPathMap) {
if (typeof nextPathOrPathMap === 'object') {
if (nextPathOrPathMap.$type) {
hasChildren = false;
} else {
hasChildren = Object.keys(nextPathOrPathMap).length > 0;
}
}
}
var next;
if (key === null || jsonQuery && key === '__null') {
next = curr;
} else {
next = curr[key];
permuteOptimized.push(key);
permuteRequested.push(key);
}
if (next) {
var nType = next.$type;
var value = nType && next.value || next;
if (jsonQuery && hasChildren || !jsonQuery && depth < pathOrJSON.length) {
if (nType && nType === $path && !isExpired(next)) {
if (asJSONG) {
onValue(model, next, seedOrFunction, outerResults, false, permuteOptimized, permutePosition, outputFormat);
}
var ref = followReference(model, root, root, next, value, seedOrFunction, outputFormat);
fromReference = true;
next = ref[0];
var refPath = ref[1];
permuteOptimized = [];
for (i = 0, len = refPath.length; i < len; i++) {
permuteOptimized[i] = refPath[i];
}
}
}
}
walk(model, root, next, nextPathOrPathMap, depth, seedOrFunction, permutePosition, outerResults, permuteOptimized, permuteRequested, inputFormat, outputFormat, fromReference);
if (!memo.done) {
key = permuteKey(k, memo);
}
} while (!memo.done);
}
}
function evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference) {
// BaseCase: This position does not exist, emit missing.
if (!curr) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
}
return true;
}
var currType = curr.$type;
positionalInfo = positionalInfo || [];
// The Base Cases. There is a type, therefore we have hit a 'leaf' node.
if (currType === $error) {
if (fromReference) {
requestedPath.push(null);
}
if (outputFormat === 'JSONG' || model._treatErrorsAsValues) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onError(model, curr, requestedPath, optimizedPath, outerResults);
}
}
// Else we have found a value, emit the current position information.
else {
if (isExpired(curr)) {
if (!curr[__invalidated]) {
splice(model, curr);
removeHardlink(curr);
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
} else {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
}
}
return true;
}
module.exports = walk;
},{"../internal/invalidated":69,"./../types/error":139,"./../types/path":140,"./followReference":44,"./onError":54,"./onMissing":55,"./onValue":56,"./util/hardlink":58,"./util/isExpired":59,"./util/isMaterialzed":60,"./util/lru":62,"./util/permuteKey":63}],52:[function(_dereq_,module,exports){
var walk = _dereq_('./getWalk');
module.exports = {
getAsJSON: _dereq_('./getAsJSON')(walk),
getAsJSONG: _dereq_('./getAsJSONG')(walk),
getAsValues: _dereq_('./getAsValues')(walk),
getAsPathMap: _dereq_('./getAsPathMap')(walk),
getValueSync: _dereq_('./getValueSync'),
getBoundValue: _dereq_('./getBoundValue'),
setCache: _dereq_('./legacy_setCache')
};
},{"./getAsJSON":45,"./getAsJSONG":46,"./getAsPathMap":47,"./getAsValues":48,"./getBoundValue":49,"./getValueSync":50,"./getWalk":51,"./legacy_setCache":53}],53:[function(_dereq_,module,exports){
/* istanbul ignore next */
var NOOP = function NOOP() {},
__GENERATION_GUID = 0,
__GENERATION_VERSION = 0,
__CONTAINER = "__reference_container",
__CONTEXT = "__context",
__GENERATION = "__generation",
__GENERATION_UPDATED = "__generation_updated",
__INVALIDATED = "__invalidated",
__KEY = "__key",
__KEYS = "__keys",
__IS_KEY_SET = "__is_key_set",
__NULL = "__null",
__SELF = "./",
__PARENT = "../",
__REF = "__ref",
__REF_INDEX = "__ref_index",
__REFS_LENGTH = "__refs_length",
__ROOT = "/",
__OFFSET = "__offset",
__FALKOR_EMPTY_OBJECT = '__FALKOR_EMPTY_OBJECT',
__INTERNAL_KEYS = [
__CONTAINER, __CONTEXT, __GENERATION, __GENERATION_UPDATED,
__INVALIDATED, __KEY, __KEYS, __IS_KEY_SET, __NULL, __SELF,
__PARENT, __REF, __REF_INDEX, __REFS_LENGTH, __OFFSET, __ROOT
],
$TYPE = "$type",
$SIZE = "$size",
$EXPIRES = "$expires",
$TIMESTAMP = "$timestamp",
SENTINEL = "sentinel",
PATH = "ref",
ERROR = "error",
VALUE = "value",
EXPIRED = "expired",
LEAF = "leaf";
/* istanbul ignore next */
module.exports = function setCache(model, map) {
var root = model._root, expired = root.expired, depth = 0, height = 0, mapStack = [], nodes = [], nodeRoot = model._cache, nodeParent = nodeRoot, node = nodeParent, nodeType, nodeValue, nodeSize, nodeTimestamp, nodeExpires;
mapStack[0] = map;
nodes[-1] = nodeParent;
while (depth > -1) {
/* Walk Path Map */
var isTerminus = false, offset = 0, keys = void 0, index = void 0, key = void 0, isKeySet = false;
node = nodeParent = nodes[depth - 1];
depth = depth;
follow_path_map_9177:
do {
height = depth;
nodeType = node && node[$TYPE] || void 0;
nodeValue = nodeType === SENTINEL ? node[VALUE] : node;
if ((isTerminus = !((map = mapStack[offset = depth * 4]) != null && typeof map === 'object') || map[$TYPE] !== void 0 || Array.isArray(map) || !((keys = mapStack[offset + 1] || (mapStack[offset + 1] = Object.keys(map))) && ((index = mapStack[offset + 2] || (mapStack[offset + 2] = 0)) || true) && ((isKeySet = keys.length > 1) || keys.length > 0))) || (node == null || nodeType !== void 0 || typeof node !== 'object' || Array.isArray(nodeValue))) {
if ((nodeExpires = (node && node[$EXPIRES]) != null) && (nodeExpires !== 1 && (nodeExpires === 0 || nodeExpires < now())) || node != null && node[__INVALIDATED] === true) {
nodeType = void 0;
nodeValue = void 0;
node = (expired[expired.length] = node) && (node[__INVALIDATED] = true) && void 0;
}
if (!isTerminus && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue))) {
if (node == null || nodeType !== void 0 || typeof node !== 'object' || Array.isArray(nodeValue)) {
key = null;
node = node;
depth = depth;
continue follow_path_map_9177;
}
} else {
if (key != null) {
var newNode, sizeOffset, edgeSize = node && node[$SIZE] || 0;
nodeType = map && map[$TYPE] || void 0;
nV2 = nodeType ? map[VALUE] : void 0;
nodeValue = nodeType === SENTINEL ? map[VALUE] : map;
newNode = map;
if ((!nodeType || nodeType === SENTINEL || nodeType === PATH) && Array.isArray(nodeValue)) {
delete nodeValue[$SIZE];
// console.log(1);
if (nodeType) {
nodeSize = 50 + (nodeValue.length || 1);
} else {
nodeSize = nodeValue.length || 1;
}
newNode[$SIZE] = nodeSize;
nodeValue[__CONTAINER] = newNode;
} else if (nodeType === SENTINEL || nodeType === PATH) {
newNode[$SIZE] = nodeSize = 50 + (nV2 && typeof nV2.length === 'number' ? nV2.length : 1);
} else if (nodeType === ERROR) {
newNode[$SIZE] = nodeSize = map && map[$SIZE] || 0 || 50 + 1;
} else if (!(map != null && typeof map === 'object')) {
nodeSize = 50 + (typeof nodeValue === 'string' && nodeValue.length || 1);
nodeType = 'sentinel';
newNode = {};
newNode[VALUE] = nodeValue;
newNode[$TYPE] = nodeType;
newNode[$SIZE] = nodeSize;
} else {
nodeType = newNode[$TYPE] = nodeType || GROUP;
newNode[$SIZE] = nodeSize = map && map[$SIZE] || 0 || 50 + 1;
}
;
if (node !== newNode && (node != null && typeof node === 'object')) {
var nodeRefsLength = node[__REFS_LENGTH] || 0, destRefsLength = newNode[__REFS_LENGTH] || 0, i = -1, ref;
while (++i < nodeRefsLength) {
if ((ref = node[__REF + i]) !== void 0) {
ref[__CONTEXT] = newNode;
newNode[__REF + (destRefsLength + i)] = ref;
node[__REF + i] = void 0;
}
}
newNode[__REFS_LENGTH] = nodeRefsLength + destRefsLength;
node[__REFS_LENGTH] = ref = void 0;
var invParent = nodeParent, invChild = node, invKey = key, keys$2, index$2, offset$2, childType, childValue, isBranch, stack = [
nodeParent,
invKey,
node
], depth$2 = 0;
while (depth$2 > -1) {
nodeParent = stack[offset$2 = depth$2 * 8];
invKey = stack[offset$2 + 1];
node = stack[offset$2 + 2];
if ((childType = stack[offset$2 + 3]) === void 0 || (childType = void 0)) {
childType = stack[offset$2 + 3] = node && node[$TYPE] || void 0 || null;
}
childValue = stack[offset$2 + 4] || (stack[offset$2 + 4] = childType === SENTINEL ? node[VALUE] : node);
if ((isBranch = stack[offset$2 + 5]) === void 0) {
isBranch = stack[offset$2 + 5] = !childType && (node != null && typeof node === 'object') && !Array.isArray(childValue);
}
if (isBranch === true) {
if ((keys$2 = stack[offset$2 + 6]) === void 0) {
keys$2 = stack[offset$2 + 6] = [];
index$2 = -1;
for (var childKey in node) {
!(!(childKey[0] !== '_' || childKey[1] !== '_') || (childKey === __SELF || childKey === __PARENT || childKey === __ROOT) || childKey[0] === '$') && (keys$2[++index$2] = childKey);
}
}
index$2 = stack[offset$2 + 7] || (stack[offset$2 + 7] = 0);
if (index$2 < keys$2.length) {
stack[offset$2 + 7] = index$2 + 1;
stack[offset$2 = ++depth$2 * 8] = node;
stack[offset$2 + 1] = invKey = keys$2[index$2];
stack[offset$2 + 2] = node[invKey];
continue;
}
}
var ref$2 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination;
if (ref$2 && Array.isArray(ref$2)) {
destination = ref$2[__CONTEXT];
if (destination) {
var i$2 = (ref$2[__REF_INDEX] || 0) - 1, n = (destination[__REFS_LENGTH] || 0) - 1;
while (++i$2 <= n) {
destination[__REF + i$2] = destination[__REF + (i$2 + 1)];
}
destination[__REFS_LENGTH] = n;
ref$2[__REF_INDEX] = ref$2[__CONTEXT] = destination = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$3, i$3 = -1, n$2 = node[__REFS_LENGTH] || 0;
while (++i$3 < n$2) {
if ((ref$3 = node[__REF + i$3]) !== void 0) {
ref$3[__CONTEXT] = node[__REF + i$3] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$2 = root, head = root$2.__head, tail = root$2.__tail, next = node.__next, prev = node.__prev;
next != null && typeof next === 'object' && (next.__prev = prev);
prev != null && typeof prev === 'object' && (prev.__next = next);
node === head && (root$2.__head = root$2.__next = next);
node === tail && (root$2.__tail = root$2.__prev = prev);
node.__next = node.__prev = void 0;
head = tail = next = prev = void 0;
;
nodeParent[invKey] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
;
delete stack[offset$2 + 0];
delete stack[offset$2 + 1];
delete stack[offset$2 + 2];
delete stack[offset$2 + 3];
delete stack[offset$2 + 4];
delete stack[offset$2 + 5];
delete stack[offset$2 + 6];
delete stack[offset$2 + 7];
--depth$2;
}
nodeParent = invParent;
node = invChild;
}
nodeParent[key] = node = newNode;
nodeType = node && node[$TYPE] || void 0;
node = !node[__SELF] && ((node[__SELF] = node) || true) && ((node[__KEY] = key) || true) && ((node[__PARENT] = nodeParent) || true) && ((node[__ROOT] = nodeRoot) || true) && (node[__GENERATION] || (node[__GENERATION] = ++__GENERATION_GUID) && node) && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue) && (nodeValue[__CONTAINER] = node)) || node;
sizeOffset = edgeSize - nodeSize;
var self = nodeParent, child = node;
while (node = nodeParent) {
nodeParent = node[__PARENT];
if ((node[$SIZE] = (node[$SIZE] || 0) - sizeOffset) <= 0 && nodeParent) {
var ref$4 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination$2;
if (ref$4 && Array.isArray(ref$4)) {
destination$2 = ref$4[__CONTEXT];
if (destination$2) {
var i$4 = (ref$4[__REF_INDEX] || 0) - 1, n$3 = (destination$2[__REFS_LENGTH] || 0) - 1;
while (++i$4 <= n$3) {
destination$2[__REF + i$4] = destination$2[__REF + (i$4 + 1)];
}
destination$2[__REFS_LENGTH] = n$3;
ref$4[__REF_INDEX] = ref$4[__CONTEXT] = destination$2 = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$5, i$5 = -1, n$4 = node[__REFS_LENGTH] || 0;
while (++i$5 < n$4) {
if ((ref$5 = node[__REF + i$5]) !== void 0) {
ref$5[__CONTEXT] = node[__REF + i$5] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$3 = root, head$2 = root$3.__head, tail$2 = root$3.__tail, next$2 = node.__next, prev$2 = node.__prev;
next$2 != null && typeof next$2 === 'object' && (next$2.__prev = prev$2);
prev$2 != null && typeof prev$2 === 'object' && (prev$2.__next = next$2);
node === head$2 && (root$3.__head = root$3.__next = next$2);
node === tail$2 && (root$3.__tail = root$3.__prev = prev$2);
node.__next = node.__prev = void 0;
head$2 = tail$2 = next$2 = prev$2 = void 0;
;
nodeParent[node[__KEY]] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
} else if (node[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
var self$2 = node, stack$2 = [], depth$3 = 0, linkPaths, ref$6, i$6, k, n$5;
while (depth$3 > -1) {
if ((linkPaths = stack$2[depth$3]) === void 0) {
i$6 = k = -1;
n$5 = node[__REFS_LENGTH] || 0;
node[__GENERATION_UPDATED] = __GENERATION_VERSION;
node[__GENERATION] = ++__GENERATION_GUID;
if ((ref$6 = node[__PARENT]) !== void 0 && ref$6[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
stack$2[depth$3] = linkPaths = new Array(n$5 + 1);
linkPaths[++k] = ref$6;
} else if (n$5 > 0) {
stack$2[depth$3] = linkPaths = new Array(n$5);
}
while (++i$6 < n$5) {
if ((ref$6 = node[__REF + i$6]) !== void 0 && ref$6[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
linkPaths[++k] = ref$6;
}
}
}
if ((node = linkPaths && linkPaths.pop()) !== void 0) {
++depth$3;
} else {
stack$2[depth$3--] = void 0;
}
}
node = self$2;
}
}
nodeParent = self;
node = child;
}
;
node = node;
break follow_path_map_9177;
}
}
if ((key = keys[index]) == null) {
node = node;
break follow_path_map_9177;
} else if (key === __NULL && ((key = null) || true) || !(!(key[0] !== '_' || key[1] !== '_') || (key === __SELF || key === __PARENT || key === __ROOT) || key[0] === '$') && ((mapStack[(depth + 1) * 4] = map[key]) || true)) {
mapStack[(depth + 1) * 4 + 3] = key;
} else {
mapStack[offset + 2] = index + 1;
node = node;
depth = depth;
continue follow_path_map_9177;
}
nodes[depth - 1] = nodeParent = node;
if (key != null) {
node = nodeParent && nodeParent[key];
if (typeof map === 'object') {
for (var key$2 in map) {
key$2[0] === '$' && key$2 !== $SIZE && (nodeParent && (nodeParent[key$2] = map[key$2]) || true);
}
map = map[key];
}
var mapType = map && map[$TYPE] || void 0;
var mapValue = mapType === SENTINEL ? map[VALUE] : map;
if ((node == null || typeof node !== 'object' || !!nodeType && nodeType !== SENTINEL && !Array.isArray(nodeValue)) && (!mapType && (map != null && typeof map === 'object') && !Array.isArray(mapValue))) {
nodeType = void 0;
nodeValue = {};
nodeSize = node && node[$SIZE] || 0;
if (node !== nodeValue && (node != null && typeof node === 'object')) {
var nodeRefsLength$2 = node[__REFS_LENGTH] || 0, destRefsLength$2 = nodeValue[__REFS_LENGTH] || 0, i$7 = -1, ref$7;
while (++i$7 < nodeRefsLength$2) {
if ((ref$7 = node[__REF + i$7]) !== void 0) {
ref$7[__CONTEXT] = nodeValue;
nodeValue[__REF + (destRefsLength$2 + i$7)] = ref$7;
node[__REF + i$7] = void 0;
}
}
nodeValue[__REFS_LENGTH] = nodeRefsLength$2 + destRefsLength$2;
node[__REFS_LENGTH] = ref$7 = void 0;
var invParent$2 = nodeParent, invChild$2 = node, invKey$2 = key, keys$3, index$3, offset$3, childType$2, childValue$2, isBranch$2, stack$3 = [
nodeParent,
invKey$2,
node
], depth$4 = 0;
while (depth$4 > -1) {
nodeParent = stack$3[offset$3 = depth$4 * 8];
invKey$2 = stack$3[offset$3 + 1];
node = stack$3[offset$3 + 2];
if ((childType$2 = stack$3[offset$3 + 3]) === void 0 || (childType$2 = void 0)) {
childType$2 = stack$3[offset$3 + 3] = node && node[$TYPE] || void 0 || null;
}
childValue$2 = stack$3[offset$3 + 4] || (stack$3[offset$3 + 4] = childType$2 === SENTINEL ? node[VALUE] : node);
if ((isBranch$2 = stack$3[offset$3 + 5]) === void 0) {
isBranch$2 = stack$3[offset$3 + 5] = !childType$2 && (node != null && typeof node === 'object') && !Array.isArray(childValue$2);
}
if (isBranch$2 === true) {
if ((keys$3 = stack$3[offset$3 + 6]) === void 0) {
keys$3 = stack$3[offset$3 + 6] = [];
index$3 = -1;
for (var childKey$2 in node) {
!(!(childKey$2[0] !== '_' || childKey$2[1] !== '_') || (childKey$2 === __SELF || childKey$2 === __PARENT || childKey$2 === __ROOT) || childKey$2[0] === '$') && (keys$3[++index$3] = childKey$2);
}
}
index$3 = stack$3[offset$3 + 7] || (stack$3[offset$3 + 7] = 0);
if (index$3 < keys$3.length) {
stack$3[offset$3 + 7] = index$3 + 1;
stack$3[offset$3 = ++depth$4 * 8] = node;
stack$3[offset$3 + 1] = invKey$2 = keys$3[index$3];
stack$3[offset$3 + 2] = node[invKey$2];
continue;
}
}
var ref$8 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination$3;
if (ref$8 && Array.isArray(ref$8)) {
destination$3 = ref$8[__CONTEXT];
if (destination$3) {
var i$8 = (ref$8[__REF_INDEX] || 0) - 1, n$6 = (destination$3[__REFS_LENGTH] || 0) - 1;
while (++i$8 <= n$6) {
destination$3[__REF + i$8] = destination$3[__REF + (i$8 + 1)];
}
destination$3[__REFS_LENGTH] = n$6;
ref$8[__REF_INDEX] = ref$8[__CONTEXT] = destination$3 = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$9, i$9 = -1, n$7 = node[__REFS_LENGTH] || 0;
while (++i$9 < n$7) {
if ((ref$9 = node[__REF + i$9]) !== void 0) {
ref$9[__CONTEXT] = node[__REF + i$9] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$4 = root, head$3 = root$4.__head, tail$3 = root$4.__tail, next$3 = node.__next, prev$3 = node.__prev;
next$3 != null && typeof next$3 === 'object' && (next$3.__prev = prev$3);
prev$3 != null && typeof prev$3 === 'object' && (prev$3.__next = next$3);
node === head$3 && (root$4.__head = root$4.__next = next$3);
node === tail$3 && (root$4.__tail = root$4.__prev = prev$3);
node.__next = node.__prev = void 0;
head$3 = tail$3 = next$3 = prev$3 = void 0;
;
nodeParent[invKey$2] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
;
delete stack$3[offset$3 + 0];
delete stack$3[offset$3 + 1];
delete stack$3[offset$3 + 2];
delete stack$3[offset$3 + 3];
delete stack$3[offset$3 + 4];
delete stack$3[offset$3 + 5];
delete stack$3[offset$3 + 6];
delete stack$3[offset$3 + 7];
--depth$4;
}
nodeParent = invParent$2;
node = invChild$2;
}
nodeParent[key] = node = nodeValue;
node = !node[__SELF] && ((node[__SELF] = node) || true) && ((node[__KEY] = key) || true) && ((node[__PARENT] = nodeParent) || true) && ((node[__ROOT] = nodeRoot) || true) && (node[__GENERATION] || (node[__GENERATION] = ++__GENERATION_GUID) && node) && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue) && (nodeValue[__CONTAINER] = node)) || node;
var self$3 = node, node$2;
while (node$2 = node) {
if (node[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
var self$4 = node, stack$4 = [], depth$5 = 0, linkPaths$2, ref$10, i$10, k$2, n$8;
while (depth$5 > -1) {
if ((linkPaths$2 = stack$4[depth$5]) === void 0) {
i$10 = k$2 = -1;
n$8 = node[__REFS_LENGTH] || 0;
node[__GENERATION_UPDATED] = __GENERATION_VERSION;
node[__GENERATION] = ++__GENERATION_GUID;
if ((ref$10 = node[__PARENT]) !== void 0 && ref$10[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
stack$4[depth$5] = linkPaths$2 = new Array(n$8 + 1);
linkPaths$2[++k$2] = ref$10;
} else if (n$8 > 0) {
stack$4[depth$5] = linkPaths$2 = new Array(n$8);
}
while (++i$10 < n$8) {
if ((ref$10 = node[__REF + i$10]) !== void 0 && ref$10[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
linkPaths$2[++k$2] = ref$10;
}
}
}
if ((node = linkPaths$2 && linkPaths$2.pop()) !== void 0) {
++depth$5;
} else {
stack$4[depth$5--] = void 0;
}
}
node = self$4;
}
node = node$2[__PARENT];
}
node = self$3;
}
}
node = node;
depth = depth + 1;
continue follow_path_map_9177;
} while (true);
node = node;
var offset$4 = depth * 4, keys$4, index$4;
do {
delete mapStack[offset$4 + 0];
delete mapStack[offset$4 + 1];
delete mapStack[offset$4 + 2];
delete mapStack[offset$4 + 3];
} while ((keys$4 = mapStack[(offset$4 = 4 * --depth) + 1]) && ((index$4 = mapStack[offset$4 + 2]) || true) && (mapStack[offset$4 + 2] = ++index$4) >= keys$4.length);
}
return nodeRoot;
}
},{}],54:[function(_dereq_,module,exports){
var lru = _dereq_('./util/lru');
var clone = _dereq_('./util/clone');
var promote = lru.promote;
module.exports = function onError(model, node, permuteRequested, permuteOptimized, outerResults) {
outerResults.errors.push({path: permuteRequested, value: node.value});
promote(model, node);
if (permuteOptimized) {
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
};
},{"./util/clone":57,"./util/lru":62}],55:[function(_dereq_,module,exports){
var support = _dereq_('./util/support');
var fastCat = support.fastCat,
fastCatSkipNulls = support.fastCatSkipNulls,
fastCopy = support.fastCopy;
var isExpired = _dereq_('./util/isExpired');
var spreadJSON = _dereq_('./util/spreadJSON');
var clone = _dereq_('./util/clone');
module.exports = function onMissing(model, node, path, depth, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat) {
var pathSlice;
if (Array.isArray(path)) {
if (depth < path.length) {
pathSlice = fastCopy(path, depth);
} else {
pathSlice = [];
}
concatAndInsertMissing(pathSlice, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat);
} else {
pathSlice = [];
spreadJSON(path, pathSlice);
for (var i = 0, len = pathSlice.length; i < len; i++) {
concatAndInsertMissing(pathSlice[i], outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, true);
}
}
};
function concatAndInsertMissing(remainingPath, results, permuteRequested, permuteOptimized, permutePosition, outputFormat, __null) {
var i = 0, len;
if (__null) {
for (i = 0, len = remainingPath.length; i < len; i++) {
if (remainingPath[i] === '__null') {
remainingPath[i] = null;
}
}
}
if (outputFormat === 'JSON') {
permuteRequested = fastCat(permuteRequested, remainingPath);
for (i = 0, len = permutePosition.length; i < len; i++) {
var idx = permutePosition[i];
var r = permuteRequested[idx];
permuteRequested[idx] = [r];
}
results.requestedMissingPaths.push(permuteRequested);
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
} else {
results.requestedMissingPaths.push(fastCat(permuteRequested, remainingPath));
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
}
}
},{"./util/clone":57,"./util/isExpired":59,"./util/spreadJSON":64,"./util/support":65}],56:[function(_dereq_,module,exports){
var lru = _dereq_('./util/lru');
var clone = _dereq_('./util/clone');
var promote = lru.promote;
var $path = _dereq_('./../types/path');
var $sentinel = _dereq_('./../types/sentinel');
var $error = _dereq_('./../types/error');
module.exports = function onValue(model, node, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, fromReference) {
var i, len, k, key, curr, prev, prevK;
var materialized = false, valueNode;
if (node) {
promote(model, node);
}
if (!node || node.value === undefined) {
materialized = model._materialized;
}
// materialized
if (materialized) {
valueNode = {$type: $sentinel};
}
// Boxed Mode & Reference Node & Error node (only happens when model is in treat errors as values).
else if (model._boxed) {
valueNode = clone(node);
}
else if (node.$type === $path || node.$type === $error) {
if (outputFormat === 'JSONG') {
valueNode = clone(node);
} else {
valueNode = node.value;
}
}
else {
if (outputFormat === 'JSONG') {
if (typeof node.value === 'object') {
valueNode = clone(node);
} else {
valueNode = node.value;
}
} else {
valueNode = node.value;
}
}
if (permuteRequested) {
if (fromReference && permuteRequested[permuteRequested.length - 1] !== null) {
permuteRequested.push(null);
}
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
switch (outputFormat) {
case 'Values':
// in any subscription situation, onNexts are always provided, even as a noOp.
seedOrFunction({path: permuteRequested, value: valueNode});
break;
case 'PathMap':
len = permuteRequested.length - 1;
if (len === -1) {
seedOrFunction.json = valueNode;
} else {
curr = seedOrFunction.json;
if (!curr) {
curr = seedOrFunction.json = {};
}
for (i = 0; i < len; i++) {
k = permuteRequested[i];
if (!curr[k]) {
curr[k] = {};
}
prev = curr;
prevK = k;
curr = curr[k];
}
k = permuteRequested[i];
if (k !== null) {
curr[k] = valueNode;
} else {
prev[prevK] = valueNode;
}
}
break;
case 'JSON':
if (seedOrFunction) {
if (permutePosition.length) {
if (!seedOrFunction.json) {
seedOrFunction.json = {};
}
curr = seedOrFunction.json;
for (i = 0, len = permutePosition.length - 1; i < len; i++) {
k = permutePosition[i];
key = permuteRequested[k];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
k = permutePosition[i];
key = permuteRequested[k];
curr[key] = valueNode;
} else {
seedOrFunction.json = valueNode;
}
}
break;
case 'JSONG':
curr = seedOrFunction.jsong;
if (!curr) {
curr = seedOrFunction.jsong = {};
seedOrFunction.paths = [];
}
for (i = 0, len = permuteOptimized.length - 1; i < len; i++) {
key = permuteOptimized[i];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
key = permuteOptimized[i];
// TODO: Special case? do string comparisons make big difference?
curr[key] = materialized ? {$type: $sentinel} : valueNode;
if (permuteRequested) {
seedOrFunction.paths.push(permuteRequested);
}
break;
}
};
},{"./../types/error":139,"./../types/path":140,"./../types/sentinel":141,"./util/clone":57,"./util/lru":62}],57:[function(_dereq_,module,exports){
// Copies the node
var prefix = _dereq_("../../internal/prefix");
module.exports = function clone(node) {
var outValue, i, len;
var keys = Object.keys(node);
outValue = {};
for (i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
if (k[0] === prefix) {
continue;
}
outValue[k] = node[k];
}
return outValue;
};
},{"../../internal/prefix":74}],58:[function(_dereq_,module,exports){
var __ref = _dereq_("../../internal/ref");
var __context = _dereq_("../../internal/context");
var __ref_index = _dereq_("../../internal/ref-index");
var __refs_length = _dereq_("../../internal/refs-length");
function createHardlink(from, to) {
// create a back reference
var backRefs = to[__refs_length] || 0;
to[__ref + backRefs] = from;
to[__refs_length] = backRefs + 1;
// create a hard reference
from[__ref_index] = backRefs;
from[__context] = to;
}
function removeHardlink(cacheObject) {
var context = cacheObject[__context];
if (context) {
var idx = cacheObject[__ref_index];
var len = context[__refs_length];
while (idx < len) {
context[__ref + idx] = context[__REF + idx + 1];
++idx;
}
context[__refs_length] = len - 1;
cacheObject[__context] = undefined;
cacheObject[__ref_index] = undefined;
}
}
module.exports = {
create: createHardlink,
remove: removeHardlink
};
},{"../../internal/context":66,"../../internal/ref":77,"../../internal/ref-index":76,"../../internal/refs-length":78}],59:[function(_dereq_,module,exports){
var now = _dereq_('../../support/now');
module.exports = function isExpired(node) {
var $expires = node.$expires === undefined && -1 || node.$expires;
return $expires !== -1 && $expires !== 1 && ($expires === 0 || $expires < now());
};
},{"../../support/now":126}],60:[function(_dereq_,module,exports){
module.exports = function isMaterialized(model) {
return model._materialized && !(model._router || model._dataSource);
};
},{}],61:[function(_dereq_,module,exports){
module.exports = function(x) {
return x.path && x.value;
};
},{}],62:[function(_dereq_,module,exports){
var __head = _dereq_("../../internal/head");
var __tail = _dereq_("../../internal/tail");
var __next = _dereq_("../../internal/next");
var __prev = _dereq_("../../internal/prev");
var __invalidated = _dereq_("../../internal/invalidated");
// [H] -> Next -> ... -> [T]
// [T] -> Prev -> ... -> [H]
function lruPromote(model, object) {
var root = model._root;
var head = root[__head];
if (head === object) {
return;
}
// First insert
if (!head) {
root[__head] = object;
return;
}
// The head and the tail need to separate
if (!root[__tail]) {
root[__head] = object;
root[__tail] = head;
object[__next] = head;
// Now tail
head[__prev] = object;
return;
}
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = undefined;
// Insert into head position
root[__head] = object;
object[__next] = head;
head[__prev] = object;
}
function lruSplice(model, object) {
var root = model._root;
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = undefined;
if (object === root[__head]) {
root[__head] = undefined;
}
if (object === root[__tail]) {
root[__tail] = undefined;
}
object[__invalidated] = true;
root.expired.push(object);
}
module.exports = {
promote: lruPromote,
splice: lruSplice
};
},{"../../internal/head":68,"../../internal/invalidated":69,"../../internal/next":71,"../../internal/prev":75,"../../internal/tail":79}],63:[function(_dereq_,module,exports){
var prefix = _dereq_("../../internal/prefix");
module.exports = function permuteKey(key, memo) {
if (memo.isArray) {
if (memo.loaded && memo.rangeOffset > memo.to) {
memo.arrOffset++;
memo.loaded = false;
}
var idx = memo.arrOffset, length = key.length;
if (idx === length) {
memo.done = true;
return '';
}
var el = key[memo.arrOffset];
var type = typeof el;
if (type === 'object') {
if (!memo.loaded) {
memo.from = el.from || 0;
memo.to = el.to || el.length && memo.from + el.length - 1 || 0;
memo.rangeOffset = memo.from;
memo.loaded = true;
}
return memo.rangeOffset++;
} else {
do {
if (type !== 'string') {
break;
}
if (el[0] !== prefix && el[0] !== '$') {
break;
}
el = key[++idx];
} while (el === undefined || idx < length);
if (el === undefined || idx === length) {
memo.done = true;
return '';
}
memo.arrOffset = idx + 1;
return el;
}
} else {
if (!memo.loaded) {
memo.from = key.from || 0;
memo.to = key.to || key.length && memo.from + key.length - 1 || 0;
memo.rangeOffset = memo.from;
memo.loaded = true;
}
if (memo.rangeOffset > memo.to) {
memo.done = true;
return '';
}
return memo.rangeOffset++;
}
};
},{"../../internal/prefix":74}],64:[function(_dereq_,module,exports){
var fastCopy = _dereq_('./support').fastCopy;
module.exports = function spreadJSON(root, bins, bin) {
bin = bin || [];
if (!bins.length) {
bins.push(bin);
}
if (!root || typeof root !== 'object' || root.$type) {
return [];
}
var keys = Object.keys(root);
if (keys.length === 1) {
bin.push(keys[0]);
spreadJSON(root[keys[0]], bins, bin);
} else {
for (var i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
var nextBin = fastCopy(bin);
nextBin.push(k);
bins.push(nextBin);
spreadJSON(root[k], bins, nextBin);
}
}
};
},{"./support":65}],65:[function(_dereq_,module,exports){
function fastCopy(arr, i) {
var a = [], len, j;
for (j = 0, i = i || 0, len = arr.length; i < len; j++, i++) {
a[j] = arr[i];
}
return a;
}
function fastCatSkipNulls(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
if (arr2[j] !== null) {
a[i++] = arr2[j];
}
}
return a;
}
function fastCat(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
a[i++] = arr2[j];
}
return a;
}
module.exports = {
fastCat: fastCat,
fastCatSkipNulls: fastCatSkipNulls,
fastCopy: fastCopy
};
},{}],66:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "context";
},{"./prefix":74}],67:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "generation";
},{"./prefix":74}],68:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "head";
},{"./prefix":74}],69:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "invalidated";
},{"./prefix":74}],70:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "key";
},{"./prefix":74}],71:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "next";
},{"./prefix":74}],72:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "offset";
},{"./prefix":74}],73:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "parent";
},{"./prefix":74}],74:[function(_dereq_,module,exports){
// This may look like an empty string, but it's actually a single zero-width-space character.
module.exports = "";
},{}],75:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "prev";
},{"./prefix":74}],76:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "ref-index";
},{"./prefix":74}],77:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "ref";
},{"./prefix":74}],78:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "refs-length";
},{"./prefix":74}],79:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "tail";
},{"./prefix":74}],80:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "version";
},{"./prefix":74}],81:[function(_dereq_,module,exports){
module.exports = {
invPathSetsAsJSON: _dereq_("./invalidate-path-sets-as-json-dense"),
invPathSetsAsJSONG: _dereq_("./invalidate-path-sets-as-json-graph"),
invPathSetsAsPathMap: _dereq_("./invalidate-path-sets-as-json-sparse"),
invPathSetsAsValues: _dereq_("./invalidate-path-sets-as-json-values")
};
},{"./invalidate-path-sets-as-json-dense":82,"./invalidate-path-sets-as-json-graph":83,"./invalidate-path-sets-as-json-sparse":84,"./invalidate-path-sets-as-json-values":85}],82:[function(_dereq_,module,exports){
module.exports = invalidate_path_sets_as_json_dense;
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var array_slice = _dereq_("../support/array-slice");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var update_graph = _dereq_("../support/update-graph");
var invalidate_node = _dereq_("../support/invalidate-node");
var collect = _dereq_("../lru/collect");
function invalidate_path_sets_as_json_dense(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots[3] = parents[3] = nodes[3] = undefined;
}
var pathset = pathsets[index];
roots.index = index;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
if (is_keyset && !!(parents[3] = json)) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
nodes[0] = node;
if (!!json) {
var type = is_object(node) && node.$type || undefined;
var jsonkey = keyset;
if (jsonkey == null) {
json = roots;
jsonkey = 3;
}
json[jsonkey] = clone(roots, node, type, node && node.value);
}
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
roots.json = roots[3];
roots.hasValue = true;
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/array-slice":105,"../support/clone-dense-json":106,"../support/get-valid-key":116,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/update-graph":137,"../walk/walk-path-set":147}],83:[function(_dereq_,module,exports){
module.exports = invalidate_path_sets_as_json_graph;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var update_graph = _dereq_("../support/update-graph");
var invalidate_node = _dereq_("../support/invalidate-node");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function invalidate_path_sets_as_json_graph(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var type = is_object(node) && node.$type || undefined;
if (is_branch) {
parents[0] = nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
clone_success(roots, requested, optimized);
roots.json = roots[1];
roots.hasValue = true;
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/update-graph":137,"../types/path":140,"../walk/walk-path-set-soft-link":146}],84:[function(_dereq_,module,exports){
module.exports = invalidate_path_sets_as_json_sparse;
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var array_slice = _dereq_("../support/array-slice");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var update_graph = _dereq_("../support/update-graph");
var invalidate_node = _dereq_("../support/invalidate-node");
var collect = _dereq_("../lru/collect");
function invalidate_path_sets_as_json_sparse(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
parents[3] = json;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
nodes[0] = node;
var type = is_object(node) && node.$type || undefined;
json[jsonkey] = clone(roots, node, type, node && node.value);
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
roots.json = roots[3];
roots.hasValue = true;
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/array-slice":105,"../support/clone-dense-json":106,"../support/get-valid-key":116,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/update-graph":137,"../walk/walk-path-set":147}],85:[function(_dereq_,module,exports){
module.exports = invalidate_path_sets_as_json_values;
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var array_slice = _dereq_("../support/array-slice");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var update_graph = _dereq_("../support/update-graph");
var invalidate_node = _dereq_("../support/invalidate-node");
var collect = _dereq_("../lru/collect");
function invalidate_path_sets_as_json_values(model, pathsets, onNext) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
return;
}
nodes[0] = node;
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || undefined;
var onNext = roots.onNext;
if (!!type && onNext) {
onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/array-slice":105,"../support/clone-dense-json":106,"../support/get-valid-key":116,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/update-graph":137,"../walk/walk-path-set":147}],86:[function(_dereq_,module,exports){
var __head = _dereq_("../internal/head");
var __tail = _dereq_("../internal/tail");
var __next = _dereq_("../internal/next");
var __prev = _dereq_("../internal/prev");
var update_graph = _dereq_("../support/update-graph");
module.exports = function(lru, expired, version, total, max, ratio) {
var targetSize = max * ratio;
var node, size;
while(!!(node = expired.pop())) {
size = node.$size || 0;
total -= size;
update_graph(node, size, version, lru);
}
if(total >= max) {
var prev = lru[__tail];
while((total >= targetSize) && !!(node = prev)) {
prev = prev[__prev];
size = node.$size || 0;
total -= size;
update_graph(node, size, version, lru);
}
if((lru[__tail] = lru[__prev] = prev) == null) {
lru[__head] = lru[__next] = undefined;
} else {
prev[__next] = undefined;
}
}
};
},{"../internal/head":68,"../internal/next":71,"../internal/prev":75,"../internal/tail":79,"../support/update-graph":137}],87:[function(_dereq_,module,exports){
var $expires_never = _dereq_("../values/expires-never");
var __head = _dereq_("../internal/head");
var __tail = _dereq_("../internal/tail");
var __next = _dereq_("../internal/next");
var __prev = _dereq_("../internal/prev");
var is_object = _dereq_("../support/is-object");
module.exports = function(root, node) {
if(is_object(node) && (node.$expires !== $expires_never)) {
var head = root[__head], tail = root[__tail],
next = node[__next], prev = node[__prev];
if (node !== head) {
(next != null && typeof next === "object") && (next[__prev] = prev);
(prev != null && typeof prev === "object") && (prev[__next] = next);
(next = head) && (head != null && typeof head === "object") && (head[__prev] = node);
(root[__head] = root[__next] = head = node);
(head[__next] = next);
(head[__prev] = undefined);
}
if (tail == null || node === tail) {
root[__tail] = root[__prev] = tail = prev || node;
}
}
return node;
};
},{"../internal/head":68,"../internal/next":71,"../internal/prev":75,"../internal/tail":79,"../support/is-object":122,"../values/expires-never":142}],88:[function(_dereq_,module,exports){
var __head = _dereq_("../internal/head");
var __tail = _dereq_("../internal/tail");
var __next = _dereq_("../internal/next");
var __prev = _dereq_("../internal/prev");
module.exports = function(root, node) {
var head = root[__head], tail = root[__tail],
next = node[__next], prev = node[__prev];
(next != null && typeof next === "object") && (next[__prev] = prev);
(prev != null && typeof prev === "object") && (prev[__next] = next);
(node === head) && (root[__head] = root[__next] = next);
(node === tail) && (root[__tail] = root[__prev] = prev);
node[__next] = node[__prev] = undefined;
head = tail = next = prev = undefined;
};
},{"../internal/head":68,"../internal/next":71,"../internal/prev":75,"../internal/tail":79}],89:[function(_dereq_,module,exports){
module.exports = {
setPathSetsAsJSON: _dereq_('./set-json-values-as-json-dense'),
setPathSetsAsJSONG: _dereq_('./set-json-values-as-json-graph'),
setPathSetsAsPathMap: _dereq_('./set-json-values-as-json-sparse'),
setPathSetsAsValues: _dereq_('./set-json-values-as-json-values'),
setPathMapsAsJSON: _dereq_('./set-json-sparse-as-json-dense'),
setPathMapsAsJSONG: _dereq_('./set-json-sparse-as-json-graph'),
setPathMapsAsPathMap: _dereq_('./set-json-sparse-as-json-sparse'),
setPathMapsAsValues: _dereq_('./set-json-sparse-as-json-values'),
setJSONGsAsJSON: _dereq_('./set-json-graph-as-json-dense'),
setJSONGsAsJSONG: _dereq_('./set-json-graph-as-json-graph'),
setJSONGsAsPathMap: _dereq_('./set-json-graph-as-json-sparse'),
setJSONGsAsValues: _dereq_('./set-json-graph-as-json-values'),
setCache: _dereq_('./set-cache')
};
},{"./set-cache":90,"./set-json-graph-as-json-dense":91,"./set-json-graph-as-json-graph":92,"./set-json-graph-as-json-sparse":93,"./set-json-graph-as-json-values":94,"./set-json-sparse-as-json-dense":95,"./set-json-sparse-as-json-graph":96,"./set-json-sparse-as-json-sparse":97,"./set-json-sparse-as-json-values":98,"./set-json-values-as-json-dense":99,"./set-json-values-as-json-graph":100,"./set-json-values-as-json-sparse":101,"./set-json-values-as-json-values":102}],90:[function(_dereq_,module,exports){
module.exports = set_cache;
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var collect = _dereq_("../lru/collect");
function set_cache(model, pathmap, error_selector) {
var roots = options([], model, error_selector);
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
roots[0] = roots.root;
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return model;
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key],
type;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/sentinel":141,"../walk/walk-path-map":145}],91:[function(_dereq_,module,exports){
module.exports = set_json_graph_as_json_dense;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var merge_node = _dereq_("../support/merge-node");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_graph_as_json_dense(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var index2 = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index3 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index3 < count2) {
json = values && values[++index2];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pathset = pathsets[index3];
roots.index = index3;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
messageParent = parents[2];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
var length = requested.length;
var offset = roots.offset;
parents[3] = json;
if (is_branch) {
parents[0] = node;
parents[2] = message;
if ((length > offset) && is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/is-object":122,"../support/merge-node":125,"../support/options":127,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../types/path":140,"../walk/walk-path-set-soft-link":146}],92:[function(_dereq_,module,exports){
module.exports = set_json_graph_as_json_graph;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-graph-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var merge_node = _dereq_("../support/merge-node");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var promote = _dereq_("../lru/promote");
var collect = _dereq_("../lru/collect");
function set_json_graph_as_json_graph(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = 0;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
messageParent = parents[2];
} else {
json = nodes[1];
parent = nodes[0];
messageParent = nodes[2];
}
var jsonkey = key;
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
parents[1] = json;
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var type = is_object(node) && node.$type || undefined;
if (is_branch) {
parents[0] = node;
parents[2] = message;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":86,"../lru/promote":87,"../support/array-clone":104,"../support/clone-graph-json":107,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/is-object":122,"../support/merge-node":125,"../support/options":127,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../types/path":140,"../walk/walk-path-set-soft-link":146}],93:[function(_dereq_,module,exports){
module.exports = set_json_graph_as_json_sparse;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var merge_node = _dereq_("../support/merge-node");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_graph_as_json_sparse(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
messageParent = parents[2];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
parents[3] = json;
if (is_branch) {
var length = requested.length;
var offset = roots.offset;
var type = is_object(node) && node.$type || undefined;
parents[0] = node;
parents[2] = message;
if ((length > offset) && (!type || type == $path)) {
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/is-object":122,"../support/merge-node":125,"../support/options":127,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../types/path":140,"../walk/walk-path-set-soft-link":146}],94:[function(_dereq_,module,exports){
module.exports = set_json_graph_as_json_values;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var array_slice = _dereq_("../support/array-slice");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var merge_node = _dereq_("../support/merge-node");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_graph_as_json_values(model, envelopes, onNext, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset) {
var parent, messageParent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
messageParent = parents[2];
} else {
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
if (is_branch) {
parents[0] = node;
parents[2] = message;
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_slice(requested, roots.offset),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/array-slice":105,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/is-object":122,"../support/merge-node":125,"../support/options":127,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../types/path":140,"../walk/walk-path-set-soft-link":146}],95:[function(_dereq_,module,exports){
module.exports = set_json_sparse_as_json_dense;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-map");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_sparse_as_json_dense(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pathmap = pathmaps[index];
roots.index = index;
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
if (is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-map":133,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-map":145}],96:[function(_dereq_,module,exports){
module.exports = set_json_sparse_as_json_graph;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-graph-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-map");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var promote = _dereq_("../lru/promote");
var collect = _dereq_("../lru/collect");
function set_json_sparse_as_json_graph(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
type = node.$type;
parents[0] = nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":86,"../lru/promote":87,"../support/array-clone":104,"../support/clone-graph-json":107,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-map":133,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-map-soft-link":144}],97:[function(_dereq_,module,exports){
module.exports = set_json_sparse_as_json_sparse;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-map");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_sparse_as_json_sparse(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-map":133,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-map":145}],98:[function(_dereq_,module,exports){
module.exports = set_path_map_as_json_values;
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-map");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_path_map_as_json_values(model, pathmaps, onNext, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-map":133,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/sentinel":141,"../walk/walk-path-map":145}],99:[function(_dereq_,module,exports){
module.exports = set_json_values_as_json_dense;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var invalidate_node = _dereq_("../support/invalidate-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_values_as_json_dense(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
roots.index = index;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
if (is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-set":147}],100:[function(_dereq_,module,exports){
module.exports = set_json_values_as_json_graph;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-graph-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var invalidate_node = _dereq_("../support/invalidate-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var promote = _dereq_("../lru/promote");
var collect = _dereq_("../lru/collect");
function set_json_values_as_json_graph(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
type = node.$type;
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":86,"../lru/promote":87,"../support/array-clone":104,"../support/clone-graph-json":107,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-set-soft-link":146}],101:[function(_dereq_,module,exports){
module.exports = set_json_values_as_json_sparse;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var invalidate_node = _dereq_("../support/invalidate-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_values_as_json_sparse(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-set":147}],102:[function(_dereq_,module,exports){
module.exports = set_json_values_as_json_values;
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var invalidate_node = _dereq_("../support/invalidate-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_values_as_json_values(model, pathvalues, onNext, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized, nodes)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key], type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/sentinel":141,"../walk/walk-path-set":147}],103:[function(_dereq_,module,exports){
module.exports = function(array, value) {
var i = -1;
var n = array.length;
var array2 = new Array(n + 1);
while(++i < n) { array2[i] = array[i]; }
array2[i] = value;
return array2;
};
},{}],104:[function(_dereq_,module,exports){
module.exports = function(array) {
var i = -1;
var n = array.length;
var array2 = new Array(n);
while(++i < n) { array2[i] = array[i]; }
return array2;
};
},{}],105:[function(_dereq_,module,exports){
module.exports = function(array, index) {
var i = -1;
var n = array.length - index;
var array2 = new Array(n);
while(++i < n) { array2[i] = array[i + index]; }
return array2;
};
},{}],106:[function(_dereq_,module,exports){
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("./clone");
module.exports = function(roots, node, type, value) {
if(node == null || value === undefined) {
return { $type: $sentinel };
}
if(roots.boxed == true) {
return !!type && clone(node) || node;
}
return value;
}
},{"../types/sentinel":141,"./clone":113}],107:[function(_dereq_,module,exports){
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("./clone");
var is_primitive = _dereq_("./is-primitive");
module.exports = function(roots, node, type, value) {
if(node == null || value === undefined) {
return { $type: $sentinel };
}
if(roots.boxed == true) {
return !!type && clone(node) || node;
}
if(!type || (type === $sentinel && is_primitive(value))) {
return value;
}
return clone(node);
}
},{"../types/sentinel":141,"./clone":113,"./is-primitive":123}],108:[function(_dereq_,module,exports){
var clone_requested = _dereq_("./clone-requested-path");
var clone_optimized = _dereq_("./clone-optimized-path");
var walk_path_map = _dereq_("../walk/walk-path-map-soft-link");
var is_object = _dereq_("./is-object");
var empty = [];
module.exports = function(roots, pathmap, keys_stack, depth, requested, optimized) {
var patset_keys = explode_keys(pathmap, keys_stack.concat(), depth);
var pathset = patset_keys.map(function(keys) {
keys = keys.filter(function(key) { return key != "null"; });
switch(keys.length) {
case 0:
return null;
case 1:
return keys[0];
default:
return keys;
}
});
roots.requestedMissingPaths.push(clone_requested(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(clone_optimized(optimized, pathset, depth));
}
function explode_keys(pathmap, keys_stack, depth) {
if(is_object(pathmap)) {
var keys = Object.keys(pathmap);
var keys2 = keys_stack[depth] || (keys_stack[depth] = []);
keys2.push.apply(keys2, keys);
keys.forEach(function(key) {
explode_keys(pathmap[key], keys_stack, depth + 1);
});
}
return keys_stack;
}
},{"../walk/walk-path-map-soft-link":144,"./clone-optimized-path":110,"./clone-requested-path":111,"./is-object":122}],109:[function(_dereq_,module,exports){
var clone_requested_path = _dereq_("./clone-requested-path");
var clone_optimized_path = _dereq_("./clone-optimized-path");
module.exports = function(roots, pathset, depth, requested, optimized) {
roots.requestedMissingPaths.push(clone_requested_path(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(clone_optimized_path(optimized, pathset, depth));
}
},{"./clone-optimized-path":110,"./clone-requested-path":111}],110:[function(_dereq_,module,exports){
module.exports = function(optimized, pathset, depth) {
var x;
var i = -1;
var j = depth - 1;
var n = optimized.length;
var m = pathset.length;
var array2 = [];
while(++i < n) {
array2[i] = optimized[i];
}
while(++j < m) {
if((x = pathset[j]) != null) {
array2[i++] = x;
}
}
return array2;
}
},{}],111:[function(_dereq_,module,exports){
var is_object = _dereq_("./is-object");
module.exports = function(bound, requested, pathset, depth, index) {
var x;
var i = -1;
var j = -1;
var l = 0;
var m = requested.length;
var n = bound.length;
var array2 = [];
while(++i < n) {
array2[i] = bound[i];
}
while(++j < m) {
if((x = requested[j]) != null) {
if(is_object(pathset[l++])) {
array2[i++] = [x];
} else {
array2[i++] = x;
}
}
}
m = n + l + pathset.length - depth;
while(i < m) {
array2[i++] = pathset[l++];
}
if(index != null) {
array2.pathSetIndex = index;
}
return array2;
}
},{"./is-object":122}],112:[function(_dereq_,module,exports){
var array_slice = _dereq_("./array-slice");
var array_clone = _dereq_("./array-clone");
module.exports = function(roots, requested, optimized) {
roots.requestedPaths.push(array_slice(requested, roots.offset));
roots.optimizedPaths.push(array_clone(optimized));
}
},{"./array-clone":104,"./array-slice":105}],113:[function(_dereq_,module,exports){
var is_object = _dereq_("./is-object");
var prefix = _dereq_("../internal/prefix");
module.exports = function(value) {
var dest = value, src = dest, i = -1, n, keys, key;
if(is_object(dest)) {
dest = {};
keys = Object.keys(src);
n = keys.length;
while(++i < n) {
key = keys[i];
if(key[0] !== prefix) {
dest[key] = src[key];
}
}
}
return dest;
}
},{"../internal/prefix":74,"./is-object":122}],114:[function(_dereq_,module,exports){
var $path = _dereq_("../types/path");
var $expired = "expired";
var replace_node = _dereq_("./replace-node");
var graph_node = _dereq_("./graph-node");
var update_back_refs = _dereq_("./update-back-refs");
var is_primitive = _dereq_("./is-primitive");
var is_expired = _dereq_("./is-expired");
module.exports = function(roots, parent, node, type, key) {
if(!!type && is_expired(roots, node)) {
type = $expired;
}
if((!!type && type != $path) || is_primitive(node)) {
node = replace_node(parent, node, {}, key, roots.lru);
node = graph_node(roots[0], parent, node, key, 0);
node = update_back_refs(node, roots.version);
}
return node;
}
},{"../types/path":140,"./graph-node":117,"./is-expired":121,"./is-primitive":123,"./replace-node":130,"./update-back-refs":136}],115:[function(_dereq_,module,exports){
var __ref = _dereq_("../internal/ref");
var __context = _dereq_("../internal/context");
var __ref_index = _dereq_("../internal/ref-index");
var __refs_length = _dereq_("../internal/refs-length");
module.exports = function(node) {
var ref, i = -1, n = node[__refs_length] || 0;
while(++i < n) {
if((ref = node[__ref + i]) !== undefined) {
ref[__context] = ref[__ref_index] = node[__ref + i] = undefined;
}
}
node[__refs_length] = undefined
}
},{"../internal/context":66,"../internal/ref":77,"../internal/ref-index":76,"../internal/refs-length":78}],116:[function(_dereq_,module,exports){
module.exports = function(path) {
var key, index = path.length - 1;
do {
if((key = path[index]) != null) {
return key;
}
} while(--index > -1);
return null;
}
},{}],117:[function(_dereq_,module,exports){
var __parent = _dereq_("../internal/parent");
var __key = _dereq_("../internal/key");
var __generation = _dereq_("../internal/generation");
module.exports = function(root, parent, node, key, generation) {
node[__parent] = parent;
node[__key] = key;
node[__generation] = generation;
return node;
}
},{"../internal/generation":67,"../internal/key":70,"../internal/parent":73}],118:[function(_dereq_,module,exports){
var generation = 0;
module.exports = function() { return generation++; }
},{}],119:[function(_dereq_,module,exports){
var version = 0;
module.exports = function() { return version++; }
},{}],120:[function(_dereq_,module,exports){
module.exports = invalidate;
var is_object = _dereq_("./is-object");
var remove_node = _dereq_("./remove-node");
var prefix = _dereq_("../internal/prefix");
function invalidate(parent, node, key, lru) {
if(remove_node(parent, node, key, lru)) {
var type = is_object(node) && node.$type || undefined;
if(type == null) {
var keys = Object.keys(node);
for(var i = -1, n = keys.length; ++i < n;) {
var key = keys[i];
if(key[0] !== prefix && key[0] !== "$") {
invalidate(node, node[key], key, lru);
}
}
}
return true;
}
return false;
}
},{"../internal/prefix":74,"./is-object":122,"./remove-node":129}],121:[function(_dereq_,module,exports){
var $expires_now = _dereq_("../values/expires-now");
var $expires_never = _dereq_("../values/expires-never");
var __invalidated = _dereq_("../internal/invalidated");
var now = _dereq_("./now");
var splice = _dereq_("../lru/splice");
module.exports = function(roots, node) {
var expires = node.$expires;
if((expires != null ) && (
expires != $expires_never ) && (
expires == $expires_now || expires < now())) {
if(!node[__invalidated]) {
node[__invalidated] = true;
roots.expired.push(node);
splice(roots.lru, node);
}
return true;
}
return false;
}
},{"../internal/invalidated":69,"../lru/splice":88,"../values/expires-never":142,"../values/expires-now":143,"./now":126}],122:[function(_dereq_,module,exports){
var obj_typeof = "object";
module.exports = function(value) {
return value != null && typeof value == obj_typeof;
}
},{}],123:[function(_dereq_,module,exports){
var obj_typeof = "object";
module.exports = function(value) {
return value == null || typeof value != obj_typeof;
}
},{}],124:[function(_dereq_,module,exports){
module.exports = key_to_keyset;
var __offset = _dereq_("../internal/offset");
var is_array = Array.isArray;
var is_object = _dereq_("./is-object");
function key_to_keyset(key, iskeyset) {
if(iskeyset) {
if(is_array(key)) {
key = key[key[__offset]];
return key_to_keyset(key, is_object(key));
} else {
return key[__offset];
}
}
return key;
}
},{"../internal/offset":72,"./is-object":122}],125:[function(_dereq_,module,exports){
var $self = "./";
var $path = _dereq_("../types/path");
var $sentinel = _dereq_("../types/sentinel");
var $expires_now = _dereq_("../values/expires-now");
var is_object = _dereq_("./is-object");
var is_primitive = _dereq_("./is-primitive");
var is_expired = _dereq_("./is-expired");
var promote = _dereq_("../lru/promote");
var wrap_node = _dereq_("./wrap-node");
var graph_node = _dereq_("./graph-node");
var replace_node = _dereq_("../support/replace-node");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("./inc-generation");
var invalidate_node = _dereq_("./invalidate-node");
module.exports = function(roots, parent, node, messageParent, message, key) {
var type, messageType, node_is_object, message_is_object;
// If the cache and message are the same, we can probably return early:
// - If they're both null, return null.
// - If they're both branches, return the branch.
// - If they're both edges, continue below.
if(node == message) {
if(node == null) {
return null;
} else if(node_is_object = is_object(node)) {
type = node.$type;
if(type == null) {
if(node[$self] == null) {
return graph_node(roots[0], parent, node, key, 0);
}
return node;
}
}
} else if(node_is_object = is_object(node)) {
type = node.$type;
}
var value, messageValue;
if(type == $path) {
if(message == null) {
// If the cache is an expired reference, but the message
// is empty, remove the cache value and return undefined
// so we build a missing path.
if(is_expired(roots, node)) {
invalidate_node(parent, node, key, roots.lru);
return undefined;
}
// If the cache has a reference and the message is empty,
// leave the cache alone and follow the reference.
return node;
} else if(message_is_object = is_object(message)) {
messageType = message.$type;
// If the cache and the message are both references,
// check if we need to replace the cache reference.
if(messageType == $path) {
if(node === message) {
// If the cache and message are the same reference,
// we performed a whole-branch merge of one of the
// grandparents. If we've previously graphed this
// reference, break early.
if(node[$self] != null) {
return node;
}
}
// If the message doesn't expire immediately and is newer than the
// cache (or either cache or message don't have timestamps), attempt
// to use the message value.
// Note: Number and `undefined` compared LT/GT to `undefined` is `false`.
else if((
is_expired(roots, message) === false) && ((
message.$timestamp < node.$timestamp) === false)) {
// Compare the cache and message references.
// - If they're the same, break early so we don't insert.
// - If they're different, replace the cache reference.
value = node.value;
messageValue = message.value;
var count = value.length;
// If the reference lengths are equal, check their keys for equality.
if(count === messageValue.length) {
while(--count > -1) {
// If any of their keys are different, replace the reference
// in the cache with the reference in the message.
if(value[count] !== messageValue[count]) {
break;
}
}
// If all their keys are equal, leave the cache value alone.
if(count === -1) {
return node;
}
}
}
}
}
} else {
if(message_is_object = is_object(message)) {
messageType = message.$type;
}
if(node_is_object && !type) {
// Otherwise if the cache is a branch and the message is either
// null or also a branch, continue with the cache branch.
if(message == null || (message_is_object && !messageType)) {
return node;
}
}
}
// If the message is an expired edge, report it back out so we don't build a missing path, but
// don't insert it into the cache. If a value exists in the cache that didn't come from a
// whole-branch grandparent merge, remove the cache value.
if(!!messageType && !!message[$self] && is_expired(roots, message)) {
if(node_is_object && node != message) {
invalidate_node(parent, node, key, roots.lru);
}
return message;
}
// If the cache is a value, but the message is a branch, merge the branch over the value.
else if(!!type && message_is_object && !messageType) {
node = replace_node(parent, node, message, key, roots.lru);
return graph_node(roots[0], parent, node, key, 0);
}
// If the message is a value, insert it into the cache.
else if(!message_is_object || !!messageType) {
var offset = 0;
// If we've arrived at this message value, but didn't perform a whole-branch merge
// on one of its ancestors, replace the cache node with the message value.
if(node != message) {
messageValue || (messageValue = !!messageType ? message.value : message);
message = wrap_node(message, messageType, messageValue);
var size = node_is_object && node.$size || 0;
var messageSize = message.$size;
offset = size - messageSize;
node = replace_node(parent, node, message, key, roots.lru);
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// If the cache and the message are the same value, we branch-merged one of its
// ancestors. Give the message a $size and $type, attach its graph pointers, and
// update the cache sizes and generations.
else if(node_is_object && node[$self] == null) {
node = parent[key] = wrap_node(node, type, node.value);
offset = -node.$size;
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// Otherwise, cache and message are the same primitive value. Wrap in a sentinel and insert.
else {
node = parent[key] = wrap_node(node, type, node);
offset = -node.$size;
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// If the node is already expired, return undefined to build a missing path.
// if(is_expired(roots, node)) {
// return undefined;
// }
// Promote the message edge in the LRU.
promote(roots.lru, node);
}
// If we get here, the cache is empty and the message is a branch.
// Merge the whole branch over.
else if(node == null) {
node = parent[key] = graph_node(roots[0], parent, message, key, 0);
}
return node;
}
},{"../lru/promote":87,"../support/replace-node":130,"../support/update-graph":137,"../types/path":140,"../types/sentinel":141,"../values/expires-now":143,"./graph-node":117,"./inc-generation":118,"./invalidate-node":120,"./is-expired":121,"./is-object":122,"./is-primitive":123,"./wrap-node":138}],126:[function(_dereq_,module,exports){
module.exports = Date.now;
},{}],127:[function(_dereq_,module,exports){
var inc_version = _dereq_("../support/inc-version");
var getBoundValue = _dereq_('../get/getBoundValue');
module.exports = function(options, model, error_selector) {
var bound = options.bound || (options.bound = model._path || []);
var root = options.root || (options.root = model._cache);
var nodes = options.nodes || (options.nodes = []);
var lru = options.lru || (options.lru = model._root);
options.expired || (options.expired = lru.expired);
options.errors || (options.errors = []);
options.requestedPaths || (options.requestedPaths = []);
options.optimizedPaths || (options.optimizedPaths = []);
options.requestedMissingPaths || (options.requestedMissingPaths = []);
options.optimizedMissingPaths || (options.optimizedMissingPaths = []);
options.boxed = model._boxed || false;
options.materialized = model._materialized;
options.errorsAsValues = model._treatErrorsAsValues || false;
options.headless = model._dataSource == null;
options.version = inc_version();
options.offset || (options.offset = 0);
options.error_selector = error_selector || model._errorSelector;
if(bound.length) {
nodes[0] = getBoundValue(model, bound).value;
} else {
nodes[0] = root;
}
return options;
};
},{"../get/getBoundValue":49,"../support/inc-version":119}],128:[function(_dereq_,module,exports){
module.exports = permute_keyset;
var __offset = _dereq_("../internal/offset");
var is_array = Array.isArray;
var is_object = _dereq_("./is-object");
function permute_keyset(key) {
if(is_array(key)) {
if(key[__offset] === undefined) {
key[__offset] = -1;
if(key.length == 0) {
return false;
}
}
if(++key[__offset] >= key.length) {
return permute_keyset(key[key[__offset] = -1]);
} else {
return true;
}
} else if(is_object(key)) {
if(key[__offset] === undefined) {
key[__offset] = (key.from || (key.from = 0)) - 1;
if(key.to === undefined) {
if(key.length === undefined) {
throw new Error("Range keysets must specify at least one index to retrieve.");
} else if(key.length === 0) {
return false;
}
key.to = key.from + (key.length || 1) - 1;
}
}
if(++key[__offset] > key.to) {
key[__offset] = key.from - 1;
return false;
}
return true;
}
return false;
}
},{"../internal/offset":72,"./is-object":122}],129:[function(_dereq_,module,exports){
var $path = _dereq_("../types/path");
var __parent = _dereq_("../internal/parent");
var unlink = _dereq_("./unlink");
var delete_back_refs = _dereq_("./delete-back-refs");
var splice = _dereq_("../lru/splice");
var is_object = _dereq_("./is-object");
module.exports = function(parent, node, key, lru) {
if(is_object(node)) {
var type = node.$type;
if(!!type) {
if(type == $path) { unlink(node); }
splice(lru, node);
}
delete_back_refs(node);
parent[key] = node[__parent] = undefined;
return true;
}
return false;
}
},{"../internal/parent":73,"../lru/splice":88,"../types/path":140,"./delete-back-refs":115,"./is-object":122,"./unlink":135}],130:[function(_dereq_,module,exports){
var transfer_back_refs = _dereq_("./transfer-back-refs");
var invalidate_node = _dereq_("./invalidate-node");
module.exports = function(parent, node, replacement, key, lru) {
if(node != null && node !== replacement && typeof node == "object") {
transfer_back_refs(node, replacement);
invalidate_node(parent, node, key, lru);
}
return parent[key] = replacement;
}
},{"./invalidate-node":120,"./transfer-back-refs":131}],131:[function(_dereq_,module,exports){
var __ref = _dereq_("../internal/ref");
var __context = _dereq_("../internal/context");
var __refs_length = _dereq_("../internal/refs-length");
module.exports = function(node, dest) {
var nodeRefsLength = node[__refs_length] || 0,
destRefsLength = dest[__refs_length] || 0,
i = -1, ref;
while(++i < nodeRefsLength) {
ref = node[__ref + i];
if(ref !== undefined) {
ref[__context] = dest;
dest[__ref + (destRefsLength + i)] = ref;
node[__ref + i] = undefined;
}
}
dest[__refs_length] = nodeRefsLength + destRefsLength;
node[__refs_length] = ref = undefined;
}
},{"../internal/context":66,"../internal/ref":77,"../internal/refs-length":78}],132:[function(_dereq_,module,exports){
var $error = _dereq_("../types/error");
var promote = _dereq_("../lru/promote");
var array_clone = _dereq_("./array-clone");
module.exports = function(roots, node, type, path) {
if(node == null) {
return false;
}
promote(roots.lru, node);
if(type != $error || roots.errorsAsValues) {
return false;
}
roots.errors.push({ path: array_clone(path), value: node.value });
return true;
};
},{"../lru/promote":87,"../types/error":139,"./array-clone":104}],133:[function(_dereq_,module,exports){
var $sentinel = _dereq_("../types/sentinel");
var clone_misses = _dereq_("./clone-missing-path-maps");
var is_expired = _dereq_("./is-expired");
module.exports = function(roots, node, type, pathmap, keys_stack, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if(node == null && dematerialized) {
clone_misses(roots, pathmap, keys_stack, depth, requested, optimized);
return true;
} else if(!!type) {
if(type == $sentinel && node.value === undefined && dematerialized && !roots.boxed) {
return true;
} else if(is_expired(roots, node)) {
clone_misses(roots, pathmap, keys_stack, depth, requested, optimized);
return true;
}
}
return false;
};
},{"../types/sentinel":141,"./clone-missing-path-maps":108,"./is-expired":121}],134:[function(_dereq_,module,exports){
var $sentinel = _dereq_("../types/sentinel");
var clone_misses = _dereq_("./clone-missing-path-sets");
var is_expired = _dereq_("./is-expired");
module.exports = function(roots, node, type, pathset, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if(node == null && dematerialized) {
clone_misses(roots, pathset, depth, requested, optimized);
return true;
} else if(!!type) {
if(type == $sentinel && node.value === undefined && dematerialized && !roots.boxed) {
return true;
} else if(is_expired(roots, node)) {
clone_misses(roots, pathset, depth, requested, optimized);
return true;
}
}
return false;
};
},{"../types/sentinel":141,"./clone-missing-path-sets":109,"./is-expired":121}],135:[function(_dereq_,module,exports){
var __ref = _dereq_("../internal/ref");
var __context = _dereq_("../internal/context");
var __ref_index = _dereq_("../internal/ref-index");
var __refs_length = _dereq_("../internal/refs-length");
module.exports = function(ref) {
var destination = ref[__context];
if(destination) {
var i = (ref[__ref_index] || 0) - 1,
n = (destination[__refs_length] || 0) - 1;
while(++i <= n) {
destination[__ref + i] = destination[__ref + (i + 1)];
}
destination[__refs_length] = n;
ref[__ref_index] = ref[__context] = destination = undefined;
}
}
},{"../internal/context":66,"../internal/ref":77,"../internal/ref-index":76,"../internal/refs-length":78}],136:[function(_dereq_,module,exports){
module.exports = update_back_refs;
var __ref = _dereq_("../internal/ref");
var __parent = _dereq_("../internal/parent");
var __version = _dereq_("../internal/version");
var __generation = _dereq_("../internal/generation");
var __refs_length = _dereq_("../internal/refs-length");
var generation = _dereq_("./inc-generation");
function update_back_refs(node, version) {
if(node && node[__version] !== version) {
node[__version] = version;
node[__generation] = generation();
update_back_refs(node[__parent], version);
var i = -1, n = node[__refs_length] || 0;
while(++i < n) {
update_back_refs(node[__ref + i], version);
}
}
return node;
}
},{"../internal/generation":67,"../internal/parent":73,"../internal/ref":77,"../internal/refs-length":78,"../internal/version":80,"./inc-generation":118}],137:[function(_dereq_,module,exports){
var __key = _dereq_("../internal/key");
var __version = _dereq_("../internal/version");
var __parent = _dereq_("../internal/parent");
var remove_node = _dereq_("./remove-node");
var update_back_refs = _dereq_("./update-back-refs");
module.exports = function(node, offset, version, lru) {
var child;
while(child = node) {
node = child[__parent];
if((child.$size = (child.$size || 0) - offset) <= 0 && node != null) {
remove_node(node, child, child[__key], lru);
} else if(child[__version] !== version) {
update_back_refs(child, version);
}
}
}
},{"../internal/key":70,"../internal/parent":73,"../internal/version":80,"./remove-node":129,"./update-back-refs":136}],138:[function(_dereq_,module,exports){
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var now = _dereq_("./now");
var clone = _dereq_("./clone");
var is_array = Array.isArray;
var is_object = _dereq_("./is-object");
module.exports = function(node, type, value) {
var dest = node, size = 0;
if(!!type) {
dest = clone(node);
size = dest.$size;
// }
// if(type == $path) {
// dest = clone(node);
// size = 50 + (value.length || 1);
// } else if(is_object(node) && (type || (type = node.$type))) {
// dest = clone(node);
// size = dest.$size;
} else {
dest = { value: value };
type = $sentinel;
}
if(size <= 0 || size == null) {
switch(typeof value) {
case "number":
case "boolean":
case "function":
case "undefined":
size = 51;
break;
case "object":
size = is_array(value) && (50 + value.length) || 51;
break;
case "string":
size = 50 + value.length;
break;
}
}
var expires = is_object(node) && node.$expires || undefined;
if(typeof expires === "number" && expires < 0) {
dest.$expires = now() + (expires * -1);
}
dest.$type = type;
dest.$size = size;
return dest;
}
},{"../types/error":139,"../types/path":140,"../types/sentinel":141,"./clone":113,"./is-object":122,"./now":126}],139:[function(_dereq_,module,exports){
module.exports = "error";
},{}],140:[function(_dereq_,module,exports){
module.exports = "ref";
},{}],141:[function(_dereq_,module,exports){
module.exports = "sentinel";
},{}],142:[function(_dereq_,module,exports){
module.exports = 1;
},{}],143:[function(_dereq_,module,exports){
module.exports = 0;
},{}],144:[function(_dereq_,module,exports){
module.exports = walk_path_map;
var prefix = _dereq_("../internal/prefix");
var $path = _dereq_("../types/path");
var walk_reference = _dereq_("./walk-reference");
var array_slice = _dereq_("../support/array-slice");
var array_clone = _dereq_("../support/array-clone");
var array_append = _dereq_("../support/array-append");
var is_expired = _dereq_("../support/is-expired");
var is_primitive = _dereq_("../support/is-primitive");
var is_object = _dereq_("../support/is-object");
var is_array = Array.isArray;
var promote = _dereq_("../lru/promote");
function walk_path_map(onNode, onEdge, pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(is_primitive(pathmap) || is_primitive(node)) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[0] = parents[0] = roots[0];
nodes[1] = parents[1] = roots[1];
nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, true, null, keyset, false);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
if(type != null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keys_stack[depth] = Object.keys(pathmap);
if(keys.length == 0) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var is_outer_keyset = keys.length > 1;
for(var i = -1, n = keys.length; ++i < n;) {
var inner_key = keys[i];
if((inner_key[0] === prefix) || (inner_key[0] === "$")) {
continue;
}
var inner_keyset = is_outer_keyset ? inner_key : keyset;
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var pathmap2 = pathmap[inner_key];
var requested2, optimized2, is_branch;
var has_child_key = false;
var is_branch = is_object(pathmap2) && !pathmap2.$type;// && !is_array(pathmap2);
if(is_branch) {
for(child_key in pathmap2) {
if((child_key[0] === prefix) || (child_key[0] === "$")) {
continue;
}
child_key = pathmap2.hasOwnProperty(child_key);
break;
}
is_branch = child_key === true;
}
if(inner_key == "null") {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
inner_key = key;
inner_keyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
if(is_branch) {
walk_path_map(onNode, onEdge,
pathmap2, keys_stack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
} else {
onEdge(pathmap2, keys_stack, depth, roots, parents2, nodes2, requested2, optimized2, inner_key, inner_keyset);
}
}
}
},{"../internal/prefix":74,"../lru/promote":87,"../support/array-append":103,"../support/array-clone":104,"../support/array-slice":105,"../support/is-expired":121,"../support/is-object":122,"../support/is-primitive":123,"../types/path":140,"./walk-reference":148}],145:[function(_dereq_,module,exports){
module.exports = walk_path_map;
var prefix = _dereq_("../internal/prefix");
var __context = _dereq_("../internal/context");
var $path = _dereq_("../types/path");
var walk_reference = _dereq_("./walk-reference");
var array_slice = _dereq_("../support/array-slice");
var array_clone = _dereq_("../support/array-clone");
var array_append = _dereq_("../support/array-append");
var is_expired = _dereq_("../support/is-expired");
var is_primitive = _dereq_("../support/is-primitive");
var is_object = _dereq_("../support/is-object");
var is_array = Array.isArray;
var promote = _dereq_("../lru/promote");
function walk_path_map(onNode, onEdge, pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(is_primitive(pathmap) || is_primitive(node)) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if(node != null) {
type = node.$type;
optimized = array_clone(reference);
nodes[0] = node;
} else {
nodes[0] = parents[0] = roots[0];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, true, null, keyset, false);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
}
if(type != null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keys_stack[depth] = Object.keys(pathmap);
if(keys.length == 0) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var is_outer_keyset = keys.length > 1;
for(var i = -1, n = keys.length; ++i < n;) {
var inner_key = keys[i];
if((inner_key[0] === prefix) || (inner_key[0] === "$")) {
continue;
}
var inner_keyset = is_outer_keyset ? inner_key : keyset;
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var pathmap2 = pathmap[inner_key];
var requested2, optimized2, is_branch;
var child_key = false;
var is_branch = is_object(pathmap2) && !pathmap2.$type;// && !is_array(pathmap2);
if(is_branch) {
for(child_key in pathmap2) {
if((child_key[0] === prefix) || (child_key[0] === "$")) {
continue;
}
child_key = pathmap2.hasOwnProperty(child_key);
break;
}
is_branch = child_key === true;
}
if(inner_key == "null") {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
inner_key = key;
inner_keyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
if(is_branch) {
walk_path_map(onNode, onEdge,
pathmap2, keys_stack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
} else {
onEdge(pathmap2, keys_stack, depth, roots, parents2, nodes2, requested2, optimized2, inner_key, inner_keyset);
}
}
}
},{"../internal/context":66,"../internal/prefix":74,"../lru/promote":87,"../support/array-append":103,"../support/array-clone":104,"../support/array-slice":105,"../support/is-expired":121,"../support/is-object":122,"../support/is-primitive":123,"../types/path":140,"./walk-reference":148}],146:[function(_dereq_,module,exports){
module.exports = walk_path_set;
var $path = _dereq_("../types/path");
var empty_array = new Array(0);
var walk_reference = _dereq_("./walk-reference");
var array_slice = _dereq_("../support/array-slice");
var array_clone = _dereq_("../support/array-clone");
var array_append = _dereq_("../support/array-append");
var is_expired = _dereq_("../support/is-expired");
var is_primitive = _dereq_("../support/is-primitive");
var is_object = _dereq_("../support/is-object");
var keyset_to_key = _dereq_("../support/keyset-to-key");
var permute_keyset = _dereq_("../support/permute-keyset");
var promote = _dereq_("../lru/promote");
function walk_path_set(onNode, onEdge, pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(depth >= pathset.length || is_primitive(node)) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[0] = parents[0] = roots[0];
nodes[1] = parents[1] = roots[1];
nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathset, roots, parents, nodes, requested, optimized, true, false, null, keyset, false);
return onEdge(pathset, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
if(type != null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outer_key = pathset[depth];
var is_outer_keyset = is_object(outer_key);
var is_branch = depth < pathset.length - 1;
var run_once = false;
while(is_outer_keyset && permute_keyset(outer_key) && (run_once = true) || (run_once = !run_once)) {
var inner_key, inner_keyset;
if(is_outer_keyset === true) {
inner_key = keyset_to_key(outer_key, true);
inner_keyset = inner_key;
} else {
inner_key = outer_key;
inner_keyset = keyset;
}
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var requested2, optimized2;
if(inner_key == null) {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
// optimized2 = optimized;
inner_key = key;
inner_keyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
walk_path_set(onNode, onEdge,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
}
}
},{"../lru/promote":87,"../support/array-append":103,"../support/array-clone":104,"../support/array-slice":105,"../support/is-expired":121,"../support/is-object":122,"../support/is-primitive":123,"../support/keyset-to-key":124,"../support/permute-keyset":128,"../types/path":140,"./walk-reference":148}],147:[function(_dereq_,module,exports){
module.exports = walk_path_set;
var prefix = _dereq_("../internal/prefix");
var __context = _dereq_("../internal/context");
var $path = _dereq_("../types/path");
var empty_array = new Array(0);
var walk_reference = _dereq_("./walk-reference");
var array_slice = _dereq_("../support/array-slice");
var array_clone = _dereq_("../support/array-clone");
var array_append = _dereq_("../support/array-append");
var is_expired = _dereq_("../support/is-expired");
var is_primitive = _dereq_("../support/is-primitive");
var is_object = _dereq_("../support/is-object");
var keyset_to_key = _dereq_("../support/keyset-to-key");
var permute_keyset = _dereq_("../support/permute-keyset");
var promote = _dereq_("../lru/promote");
function walk_path_set(onNode, onEdge, pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(depth >= pathset.length || is_primitive(node)) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if(node != null) {
type = node.$type;
optimized = array_clone(reference);
nodes[0] = node;
} else {
nodes[0] = parents[0] = roots[0];
// nodes[1] = parents[1] = roots[1];
// nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathset, roots, parents, nodes, requested, optimized, true, false, null, keyset, false);
return onEdge(pathset, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
}
if(type != null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outer_key = pathset[depth];
var is_outer_keyset = is_object(outer_key);
var is_branch = depth < pathset.length - 1;
var run_once = false;
while(is_outer_keyset && permute_keyset(outer_key) && (run_once = true) || (run_once = !run_once)) {
var inner_key, inner_keyset;
if(is_outer_keyset === true) {
inner_key = keyset_to_key(outer_key, true);
inner_keyset = inner_key;
} else {
inner_key = outer_key;
inner_keyset = keyset;
}
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var requested2, optimized2;
if(inner_key == null) {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
// optimized2 = optimized;
inner_key = key;
inner_keyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
walk_path_set(onNode, onEdge,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
}
}
},{"../internal/context":66,"../internal/prefix":74,"../lru/promote":87,"../support/array-append":103,"../support/array-clone":104,"../support/array-slice":105,"../support/is-expired":121,"../support/is-object":122,"../support/is-primitive":123,"../support/keyset-to-key":124,"../support/permute-keyset":128,"../types/path":140,"./walk-reference":148}],148:[function(_dereq_,module,exports){
module.exports = walk_reference;
var prefix = _dereq_("../internal/prefix");
var __ref = _dereq_("../internal/ref");
var __context = _dereq_("../internal/context");
var __ref_index = _dereq_("../internal/ref-index");
var __refs_length = _dereq_("../internal/refs-length");
var is_object = _dereq_("../support/is-object");
var is_primitive = _dereq_("../support/is-primitive");
var array_slice = _dereq_("../support/array-slice");
var array_append = _dereq_("../support/array-append");
function walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized) {
optimized.length = 0;
var index = -1;
var count = reference.length;
var node, key, keyset;
while(++index < count) {
node = nodes[0];
if(node == null) {
return nodes;
} else if(is_primitive(node) || node.$type) {
onNode(reference, roots, parents, nodes, requested, optimized, false, false, keyset, null, false);
return nodes;
}
do {
key = reference[index];
if(key != null) {
keyset = key;
optimized.push(key);
onNode(reference, roots, parents, nodes, requested, optimized, false, index < count - 1, key, null, false);
break;
}
} while(++index < count);
}
node = nodes[0];
if(is_object(node) && container[__context] !== node) {
var backrefs = node[__refs_length] || 0;
node[__refs_length] = backrefs + 1;
node[__ref + backrefs] = container;
container[__context] = node;
container[__ref_index] = backrefs;
}
return nodes;
}
},{"../internal/context":66,"../internal/prefix":74,"../internal/ref":77,"../internal/ref-index":76,"../internal/refs-length":78,"../support/array-append":103,"../support/array-slice":105,"../support/is-object":122,"../support/is-primitive":123}],149:[function(_dereq_,module,exports){
var falcor = _dereq_('./lib/falcor');
var get = _dereq_('./lib/get');
var set = _dereq_('./lib/set');
var inv = _dereq_('./lib/invalidate');
var prototype = falcor.Model.prototype;
prototype._getBoundValue = get.getBoundValue;
prototype._getValueSync = get.getValueSync;
prototype._getPathSetsAsValues = get.getAsValues;
prototype._getPathSetsAsJSON = get.getAsJSON;
prototype._getPathSetsAsPathMap = get.getAsPathMap;
prototype._getPathSetsAsJSONG = get.getAsJSONG;
prototype._getPathMapsAsValues = get.getAsValues;
prototype._getPathMapsAsJSON = get.getAsJSON;
prototype._getPathMapsAsPathMap = get.getAsPathMap;
prototype._getPathMapsAsJSONG = get.getAsJSONG;
prototype._setPathSetsAsJSON = set.setPathSetsAsJSON;
prototype._setPathSetsAsJSONG = set.setPathSetsAsJSONG;
prototype._setPathSetsAsPathMap = set.setPathSetsAsPathMap;
prototype._setPathSetsAsValues = set.setPathSetsAsValues;
prototype._setPathMapsAsJSON = set.setPathMapsAsJSON;
prototype._setPathMapsAsJSONG = set.setPathMapsAsJSONG;
prototype._setPathMapsAsPathMap = set.setPathMapsAsPathMap;
prototype._setPathMapsAsValues = set.setPathMapsAsValues;
prototype._setJSONGsAsJSON = set.setJSONGsAsJSON;
prototype._setJSONGsAsJSONG = set.setJSONGsAsJSONG;
prototype._setJSONGsAsPathMap = set.setJSONGsAsPathMap;
prototype._setJSONGsAsValues = set.setJSONGsAsValues;
prototype._invPathSetsAsJSON = inv.invPathSetsAsJSON;
prototype._invPathSetsAsJSONG = inv.invPathSetsAsJSONG;
prototype._invPathSetsAsPathMap = inv.invPathSetsAsPathMap;
prototype._invPathSetsAsValues = inv.invPathSetsAsValues;
// prototype._setCache = get.setCache;
prototype._setCache = set.setCache;
module.exports = falcor;
},{"./lib/falcor":5,"./lib/get":52,"./lib/invalidate":81,"./lib/set":89}]},{},[1])
(1)
});
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],149:[function(require,module,exports){
var falcor = require('falcor');
var Observable = falcor.Observable;
function XMLHttpSource(jsongUrl, timeout) {
this._jsongUrl = jsongUrl;
this._timeout = timeout || 15000;
}
XMLHttpSource.prototype = {
/**
* @inheritDoc DataSource#get
*/
get: function (pathSet) {
var method = 'GET';
var config = buildQueryObject(this._jsongUrl, method, {
path: pathSet,
method: 'get'
});
return request(method, config);
},
/**
* @inheritDoc DataSource#set
*/
set: function () {
// TODO: What to send what to send
},
/**
* @inheritDoc DataSource#call
*/
call: function (callPath, args, pathSuffix, paths) {
var method = 'GET';
var queryData = [];
args = args || [];
pathSuffix = pathSuffix || [];
paths = paths || [];
paths.forEach(function (path) {
queryData.push('path=' + encodeURIComponent(JSON.stringify(path)));
});
queryData.push('method=call');
queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
if (Array.isArray(args)) {
args.forEach(function (value) {
queryData.push('param=' + encodeURIComponent(JSON.stringify(value)));
});
}
if (Array.isArray(pathSuffix)) {
pathSuffix.forEach(function (value) {
queryData.push('pathSuffix=' + encodeURIComponent(JSON.stringify(value)));
});
}
var config = buildQueryObject(this._jsongUrl, method, queryData.join('&'));
return request(method, config);
}
};
function request(method, config) {
return Observable.create(function (observer) {
// i have to actual work now :(
var xhr = new XMLHttpRequest();
// Link the response methods
xhr.onload = onXhrLoad.bind(null, observer, xhr);
xhr.onerror = onXhrError.bind(null, observer, xhr);
xhr.ontimeout = onXhrTimeout.bind(null, observer, xhr);
// Sets information
xhr.timeout = config.timeout;
// Anything but explicit false results in true.
xhr.withCredentials = !(config.withCredentials === false);
xhr.responseType = 'json';
// Takes the url and opens the connection
xhr.open(method, config.url);
// Fills the request headers
var requestHeaders = config.requestHeaders || {};
var keys = Object.keys(requestHeaders);
keys.forEach(function (k) {
xhr.setRequestHeader(k, requestHeaders[k]);
});
// Sends the request.
xhr.send(config.data);
return function () {
// TODO: Dispose of request.
};
});
}
/*
* General handling of a successfully completed request (that had a 200 response code)
*/
function _handleXhrComplete(observer, data) {
observer.onNext(data);
observer.onCompleted();
}
/*
* General handling of ultimate failure (after appropriate retries)
*/
function _handleXhrError(observer, textStatus, errorThrown) {
if (!errorThrown) {
errorThrown = new Error(textStatus);
}
observer.onError(errorThrown);
}
function onXhrLoad(observer, xhr) {
var status,
responseData,
responseObject;
// If there's no observer, the request has been (or is being) cancelled.
if (xhr && observer) {
status = xhr.status;
responseData = xhr.responseText;
if (status >= 200 && status <= 399) {
try {
responseData = JSON.parse(responseData || '');
} catch (e) {
_handleXhrError(observer, 'invalid json', e);
}
_handleXhrComplete(observer, responseData);
} else if (status === 401 || status === 403 || status === 407) {
_handleXhrError(observer, responseData);
} else if (status === 410) {
// TODO: Retry ?
_handleXhrError(observer, responseData);
} else if (status === 408 || status === 504) {
// TODO: Retry ?
_handleXhrError(observer, responseData);
} else {
_handleXhrError(observer, responseData || ('Response code ' + status));
}
}
}
function onXhrError(observer, xhr) {
_handleXhrError(observer, xhr.statusText || 'request error');
}
function onXhrTimeout(observer) {
_handleXhrError(observer, 'request timeout');
}
function buildQueryObject(url, method, queryData) {
var qData = [];
var keys;
var data = {url: url};
if (typeof queryData === 'string') {
qData.push(queryData);
} else {
keys = Object.keys(queryData);
keys.forEach(function (k) {
var value = typeof queryData[k] === 'object' ? JSON.stringify(queryData[k]) : queryData[k];
qData.push(k + '=' + value);
});
}
if (method === 'GET') {
data.url += '?' + qData.join('&');
} else {
data.data = qData.join('&');
}
return data;
}
module.exports = XMLHttpSource;
},{"falcor":148}],150:[function(require,module,exports){
var TokenTypes = {
token: 'token',
dotSeparator: '.',
commaSeparator: ',',
openingBracket: '[',
closingBracket: ']',
openingBrace: '{',
closingBrace: '}',
escape: '\\',
space: ' ',
quote: 'quote',
unknown: 'unknown'
};
module.exports = TokenTypes;
},{}],151:[function(require,module,exports){
module.exports = {
indexer: {
nested: 'Indexers cannot be nested.',
needQuotes: 'unquoted indexers must be numeric.',
empty: 'cannot have empty indexers.',
leadingDot: 'Indexers cannot have leading dots.',
leadingComma: 'Indexers cannot have leading comma.',
requiresComma: 'Indexers require commas between indexer args.'
},
range: {
precedingNaN: 'ranges must be preceded by numbers.',
suceedingNaN: 'ranges must be suceeded by numbers.'
},
quote: {
empty: 'cannot have empty quoted keys.',
illegalEscape: 'Invalid escape character. Only quotes are escapable.'
},
unexpectedToken: 'Unexpected token.',
throwError: function(err, state, token) {
if (token) {
throw err + ' -- ' + state.parseString + ' with next token: ' + token;
}
throw err + ' -- ' + state.parseString;
}
};
},{}],152:[function(require,module,exports){
var Tokenizer = require('./tokenizer');
var head = require('./parse-tree/head');
var parser = function parser(string, extendedRules) {
return head(new Tokenizer(string, extendedRules));
};
module.exports = parser;
// Constructs the paths from paths / pathValues that have strings.
// If it does not have a string, just moves the value into the return
// results.
parser.fromPathsOrPathValues = function(paths, ext) {
var out = [];
for (i = 0, len = paths.length; i < len; i++) {
// Is the path a string
if (typeof paths[i] === 'string') {
out[i] = parser(paths[i], ext);
}
// is the path a path value with a string value.
else if (typeof paths[i].path === 'string') {
out[i] = {
path: parser(paths[i].path, ext), value: paths[i].value
};
}
// just copy it over.
else {
out[i] = paths[i];
}
}
return out;
};
// If the argument is a string, this with convert, else just return
// the path provided.
parser.fromPath = function(path, ext) {
if (typeof path === 'string') {
return parser(path, ext);
}
return path;
};
},{"./parse-tree/head":153,"./tokenizer":157}],153:[function(require,module,exports){
var TokenTypes = require('./../TokenTypes');
var Expections = require('./../exceptions');
var indexer = require('./indexer');
/**
* The top level of the parse tree. This returns the generated path
* from the tokenizer.
*/
module.exports = function head(tokenizer) {
var token = tokenizer.next();
var first = true;
var state = {
parseString: ''
};
var out = [];
while (!token.done) {
// continue to build the parse string.
state.parseString += token.token;
switch (token.type) {
case TokenTypes.token:
out[out.length] = token.token;
break;
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (first) {
// TODO: Fix me
throw 'ohh no!';
}
break;
// Spaces do nothing.
case TokenTypes.space:
// NOTE: Spaces at the top level are allowed.
// titlesById .summary is a valid path.
break;
// Its time to decend the parse tree.
case TokenTypes.openingBracket:
indexer(tokenizer, token, state, out);
break;
// TODO: Fix me
default:
throw 'ohh no!';
}
first = false;
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (first) {
// TODO: Ohh no! Fix me
throw 'ohh no!';
}
return out;
};
},{"./../TokenTypes":150,"./../exceptions":151,"./indexer":154}],154:[function(require,module,exports){
var TokenTypes = require('./../TokenTypes');
var E = require('./../exceptions');
var idxE = E.indexer;
var range = require('./range');
var quote = require('./quote');
/**
* The indexer is all the logic that happens in between
* the '[', opening bracket, and ']' closing bracket.
*/
module.exports = function indexer(tokenizer, openingToken, state, out) {
var token = tokenizer.next();
var done = false;
var allowedMaxLength = 1;
// State variables
state.indexer = [];
while (!token.done) {
// continue to build the parse string.
state.parseString += token.token;
switch (token.type) {
case TokenTypes.token:
case TokenTypes.quote:
// ensures that token adders are properly delimited.
if (state.indexer.length === allowedMaxLength) {
E.throwError(idxE.requiresComma, state);
}
break;
}
switch (token.type) {
case TokenTypes.token:
var t = +token.token;
if (isNaN(t)) {
E.throwError(idxE.needQuotes, state);
}
state.indexer[state.indexer.length] = t;
break;
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (!state.indexer.length) {
E.throwError(idxE.leadingDot, state);
}
range(tokenizer, token, state, out);
break;
// Spaces do nothing.
case TokenTypes.space:
break;
case TokenTypes.closingBracket:
done = true;
break;
// The quotes require their own tree due to what can be in it.
case TokenTypes.quote:
quote(tokenizer, token, state, out);
break;
// Its time to decend the parse tree.
case TokenTypes.openingBracket:
E.throwError(idxE.nested, state);
break;
case TokenTypes.commaSeparator:
++allowedMaxLength;
break;
default:
E.throwError(idxE.unexpectedToken, state);
}
// If done, leave loop
if (done) {
break;
}
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (state.indexer.length === 0) {
E.throwError(idxE.empty, state);
}
// Remember, if an array of 1, keySets will be generated.
if (state.indexer.length === 1) {
state.indexer = state.indexer[0];
}
out[out.length] = state.indexer;
// Clean state.
state.indexer = undefined;
};
},{"./../TokenTypes":150,"./../exceptions":151,"./quote":155,"./range":156}],155:[function(require,module,exports){
var TokenTypes = require('./../TokenTypes');
var E = require('./../exceptions');
var quoteE = E.quote;
/**
* The indexer is all the logic that happens in between
* the '[', opening bracket, and ']' closing bracket.
*/
module.exports = function quote(tokenizer, openingToken, state, out) {
var token = tokenizer.next();
var innerToken = '';
var openingQuote = openingToken.token;
var escaping = false;
var done = false;
while (!token.done) {
// continue to build the parse string.
state.parseString += token.token;
switch (token.type) {
case TokenTypes.token:
case TokenTypes.space:
case TokenTypes.dotSeparator:
case TokenTypes.commaSeparator:
case TokenTypes.openingBracket:
case TokenTypes.closingBracket:
case TokenTypes.openingBrace:
case TokenTypes.closingBrace:
if (escaping) {
E.throwError(quoteE.illegalEscape, state);
}
innerToken += token.token;
break;
case TokenTypes.quote:
// the simple case. We are escaping
if (escaping) {
innerToken += token.token;
escaping = false;
}
// its not a quote that is the opening quote
else if (token.token !== openingQuote) {
innerToken += token.token;
}
// last thing left. Its a quote that is the opening quote
// therefore we must produce the inner token of the indexer.
else {
done = true;
}
break;
case TokenTypes.escape:
escaping = true;
break;
default:
E.throwError(E.unexpectedToken, state);
}
// If done, leave loop
if (done) {
break;
}
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (innerToken.length === 0) {
E.throwError(quoteE.empty, state);
}
state.indexer[state.indexer.length] = innerToken;
};
},{"./../TokenTypes":150,"./../exceptions":151}],156:[function(require,module,exports){
var Tokenizer = require('./../tokenizer');
var TokenTypes = require('./../TokenTypes');
var E = require('./../exceptions');
/**
* The indexer is all the logic that happens in between
* the '[', opening bracket, and ']' closing bracket.
*/
module.exports = function range(tokenizer, openingToken, state, out) {
var token = tokenizer.peek();
var dotCount = 1;
var done = false;
var inclusive = true;
// Grab the last token off the stack. Must be an integer.
var idx = state.indexer.length - 1;
var from = Tokenizer.toNumber(state.indexer[idx]);
var to;
if (isNaN(from)) {
E.throwError(E.range.precedingNaN, state);
}
// Why is number checking so difficult in javascript.
while (!done && !token.done) {
switch (token.type) {
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (dotCount === 3) {
E.throwError(E.unexpectedToken, state);
}
++dotCount;
if (dotCount === 3) {
inclusive = false;
}
break;
case TokenTypes.token:
// move the tokenizer forward and save to.
to = Tokenizer.toNumber(tokenizer.next().token);
// continue to build the parse string.
state.parseString += token.token;
// throw potential error.
if (isNaN(to)) {
E.throwError(E.range.suceedingNaN, state);
}
done = true;
break;
default:
done = true;
break;
}
// Keep cycling through the tokenizer. But ranges have to peek
// before they go to the next token since there is no 'terminating'
// character.
if (!done) {
tokenizer.next();
// continue to build the parse string.
state.parseString += token.token;
// go to the next token without consuming.
token = tokenizer.peek();
}
// break and remove state information.
else {
break;
}
}
state.indexer[idx] = {from: from, to: inclusive ? to : to - 1};
};
},{"./../TokenTypes":150,"./../exceptions":151,"./../tokenizer":157}],157:[function(require,module,exports){
var TokenTypes = require('./../TokenTypes');
var DOT_SEPARATOR = '.';
var COMMA_SEPARATOR = ',';
var OPENING_BRACKET = '[';
var CLOSING_BRACKET = ']';
var OPENING_BRACE = '{';
var CLOSING_BRACE = '}';
var ESCAPE = '\\';
var DOUBLE_OUOTES = '"';
var SINGE_OUOTES = "'";
var SPACE = " ";
var SPECIAL_CHARACTERS = '\\\'"[]., ';
var EXT_SPECIAL_CHARACTERS = '\\{}\'"[]., ';
var Tokenizer = module.exports = function(string, ext) {
this._string = string;
this._idx = -1;
this._extended = ext;
};
Tokenizer.prototype = {
/**
* grabs the next token either from the peek operation or generates the
* next token.
*/
next: function() {
var nextToken = this._nextToken ?
this._nextToken : getNext(this._string, this._idx, this._extended);
this._idx = nextToken.idx;
this._nextToken = false;
return nextToken.token;
},
/**
* will peak but not increment the tokenizer
*/
peek: function() {
var nextToken = this._nextToken ?
this._nextToken : getNext(this._string, this._idx, this._extended);
this._nextToken = nextToken;
return nextToken.token;
}
};
Tokenizer.toNumber = function toNumber(x) {
if (!isNaN(+x)) {
return +x;
}
return NaN;
};
function toOutput(token, type, done) {
return {
token: token,
done: done,
type: type
};
}
function getNext(string, idx, ext) {
var output = false;
var token = '';
var specialChars = ext ?
EXT_SPECIAL_CHARACTERS : SPECIAL_CHARACTERS;
do {
done = idx + 1 >= string.length;
if (done) {
break;
}
// we have to peek at the next token
var character = string[idx + 1];
if (character !== undefined &&
specialChars.indexOf(character) === -1) {
token += character;
++idx;
continue;
}
// The token to delimiting character transition.
else if (token.length) {
break;
}
++idx;
var type;
switch (character) {
case DOT_SEPARATOR:
type = TokenTypes.dotSeparator;
break;
case COMMA_SEPARATOR:
type = TokenTypes.commaSeparator;
break;
case OPENING_BRACKET:
type = TokenTypes.openingBracket;
break;
case CLOSING_BRACKET:
type = TokenTypes.closingBracket;
break;
case OPENING_BRACE:
type = TokenTypes.openingBrace;
break;
case CLOSING_BRACE:
type = TokenTypes.closingBrace;
break;
case SPACE:
type = TokenTypes.space;
break;
case DOUBLE_OUOTES:
case SINGE_OUOTES:
type = TokenTypes.quote;
break;
case ESCAPE:
type = TokenTypes.escape;
break;
default:
type = TokenTypes.unknown;
break;
}
output = toOutput(character, type, false);
break;
} while (!done);
if (!output && token.length) {
output = toOutput(token, TokenTypes.token, false);
}
if (!output) {
output = {done: true};
}
return {
token: output,
idx: idx
};
}
},{"./../TokenTypes":150}],158:[function(require,module,exports){
'use strict';
module.exports = require('./lib')
},{"./lib":163}],159:[function(require,module,exports){
'use strict';
var asap = require('asap/raw')
function noop() {};
// States:
//
// 0 - pending
// 1 - fulfilled with _value
// 2 - rejected with _value
// 3 - adopted the state of another promise, _value
//
// once the state is no longer pending (0) it is immutable
// All `_` prefixed properties will be reduced to `_{random number}`
// at build time to obfuscate them and discourage their use.
// We don't use symbols or Object.defineProperty to fully hide them
// because the performance isn't good enough.
// to avoid using try/catch inside critical functions, we
// extract them to here.
var LAST_ERROR = null;
var IS_ERROR = {};
function getThen(obj) {
try {
return obj.then;
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
function tryCallOne(fn, a) {
try {
return fn(a);
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
function tryCallTwo(fn, a, b) {
try {
fn(a, b);
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
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')
this._71 = 0;
this._18 = null;
this._61 = [];
if (fn === noop) return;
doResolve(fn, this);
}
Promise.prototype._10 = function (onFulfilled, onRejected) {
var self = this;
return new this.constructor(function (resolve, reject) {
var res = new Promise(noop);
res.then(resolve, reject);
self._24(new Handler(onFulfilled, onRejected, res));
});
};
Promise.prototype.then = function(onFulfilled, onRejected) {
if (this.constructor !== Promise) return this._10(onFulfilled, onRejected);
var res = new Promise(noop);
this._24(new Handler(onFulfilled, onRejected, res));
return res;
};
Promise.prototype._24 = function(deferred) {
if (this._71 === 3) {
this._18._24(deferred);
return;
}
if (this._71 === 0) {
this._61.push(deferred);
return;
}
var state = this._71;
var value = this._18;
asap(function() {
var cb = state === 1 ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state === 1 ? deferred.promise._82(value) : deferred.promise._67(value))
return
}
var ret = tryCallOne(cb, value);
if (ret === IS_ERROR) {
deferred.promise._67(LAST_ERROR)
} else {
deferred.promise._82(ret)
}
});
};
Promise.prototype._82 = function(newValue) {
//Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === this) {
return this._67(new TypeError('A promise cannot be resolved with itself.'))
}
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = getThen(newValue);
if (then === IS_ERROR) {
return this._67(LAST_ERROR);
}
if (
then === this.then &&
newValue instanceof Promise &&
newValue._24 === this._24
) {
this._71 = 3;
this._18 = newValue;
for (var i = 0; i < this._61.length; i++) {
newValue._24(this._61[i]);
}
return;
} else if (typeof then === 'function') {
doResolve(then.bind(newValue), this)
return
}
}
this._71 = 1
this._18 = newValue
this._94()
}
Promise.prototype._67 = function (newValue) {
this._71 = 2
this._18 = newValue
this._94()
}
Promise.prototype._94 = function () {
for (var i = 0; i < this._61.length; i++)
this._24(this._61[i])
this._61 = null
}
function Handler(onFulfilled, onRejected, promise){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, promise) {
var done = false;
var res = tryCallTwo(fn, function (value) {
if (done) return
done = true
promise._82(value)
}, function (reason) {
if (done) return
done = true
promise._67(reason)
})
if (!done && res === IS_ERROR) {
done = true
promise._67(LAST_ERROR)
}
}
},{"asap/raw":167}],160:[function(require,module,exports){
'use strict';
var Promise = require('./core.js')
module.exports = Promise
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
setTimeout(function () {
throw err
}, 0)
})
}
},{"./core.js":159}],161:[function(require,module,exports){
'use strict';
//This file contains the ES6 extensions to the core Promises/A+ API
var Promise = require('./core.js')
var asap = require('asap/raw')
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 = 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.all = function (arr) {
var args = Array.prototype.slice.call(arr)
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
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);
}
}
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['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":159,"asap/raw":167}],162:[function(require,module,exports){
'use strict';
var Promise = require('./core.js')
module.exports = Promise
Promise.prototype['finally'] = function (f) {
return this.then(function (value) {
return Promise.resolve(f()).then(function () {
return value
})
}, function (err) {
return Promise.resolve(f()).then(function () {
throw err
})
})
}
},{"./core.js":159}],163:[function(require,module,exports){
'use strict';
module.exports = require('./core.js')
require('./done.js')
require('./finally.js')
require('./es6-extensions.js')
require('./node-extensions.js')
},{"./core.js":159,"./done.js":160,"./es6-extensions.js":161,"./finally.js":162,"./node-extensions.js":164}],164:[function(require,module,exports){
'use strict';
//This file contains then/promise specific extensions that are only useful for node.js interop
var Promise = require('./core.js')
var asap = require('asap')
module.exports = Promise
/* Static Functions */
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)
})
var res = fn.apply(self, args)
if (res && (typeof res === 'object' || typeof res === 'function') && typeof res.then === 'function') {
resolve(res)
}
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
var ctx = this
try {
return fn.apply(this, arguments).nodeify(callback, ctx)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback.call(ctx, ex)
})
}
}
}
}
Promise.prototype.nodeify = function (callback, ctx) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback.call(ctx, null, value)
})
}, function (err) {
asap(function () {
callback.call(ctx, err)
})
})
}
},{"./core.js":159,"asap":165}],165:[function(require,module,exports){
"use strict";
// rawAsap provides everything we need except exception management.
var rawAsap = require("./raw");
// RawTasks are recycled to reduce GC churn.
var freeTasks = [];
// We queue errors to ensure they are thrown in right order (FIFO).
// Array-as-queue is good enough here, since we are just dealing with exceptions.
var pendingErrors = [];
var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError);
function throwFirstError() {
if (pendingErrors.length) {
throw pendingErrors.shift();
}
}
/**
* Calls a task as soon as possible after returning, in its own event, with priority
* over other events like animation, reflow, and repaint. An error thrown from an
* event will not interrupt, nor even substantially slow down the processing of
* other events, but will be rather postponed to a lower priority event.
* @param {{call}} task A callable object, typically a function that takes no
* arguments.
*/
module.exports = asap;
function asap(task) {
var rawTask;
if (freeTasks.length) {
rawTask = freeTasks.pop();
} else {
rawTask = new RawTask();
}
rawTask.task = task;
rawAsap(rawTask);
}
// We wrap tasks with recyclable task objects. A task object implements
// `call`, just like a function.
function RawTask() {
this.task = null;
}
// The sole purpose of wrapping the task is to catch the exception and recycle
// the task object after its single use.
RawTask.prototype.call = function () {
try {
this.task.call();
} catch (error) {
if (asap.onerror) {
// This hook exists purely for testing purposes.
// Its name will be periodically randomized to break any code that
// depends on its existence.
asap.onerror(error);
} else {
// In a web browser, exceptions are not fatal. However, to avoid
// slowing down the queue of pending tasks, we rethrow the error in a
// lower priority turn.
pendingErrors.push(error);
requestErrorThrow();
}
} finally {
this.task = null;
freeTasks[freeTasks.length] = this;
}
};
},{"./raw":166}],166:[function(require,module,exports){
(function (global){
"use strict";
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including IO, animation, reflow, and redraw
// events in browsers.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
if (!queue.length) {
requestFlush();
flushing = true;
}
// Equivalent to push, but avoids a function call.
queue[queue.length] = task;
}
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// `requestFlush` is an implementation-specific method that attempts to kick
// off a `flush` event as quickly as possible. `flush` will attempt to exhaust
// the event queue before yielding to the browser's own event loop.
var requestFlush;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grow
// unbounded. To prevent memory exhaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
while (index < queue.length) {
var currentIndex = index;
// Advance the index before calling the task. This ensures that we will
// begin flushing on the next task the task throws an error.
index = index + 1;
queue[currentIndex].call();
// Prevent leaking memory for long chains of recursive calls to `asap`.
// If we call `asap` within tasks scheduled by `asap`, the queue will
// grow, but to avoid an O(n) walk for every task we execute, we don't
// shift tasks off the queue after they have been executed.
// Instead, we periodically shift 1024 tasks off the queue.
if (index > capacity) {
// Manually shift all values starting at the index back to the
// beginning of the queue.
for (var scan = 0; scan < index; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
queue.length = 0;
index = 0;
flushing = false;
}
// `requestFlush` is implemented using a strategy based on data collected from
// every available SauceLabs Selenium web driver worker at time of writing.
// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593
// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that
// have WebKitMutationObserver but not un-prefixed MutationObserver.
// Must use `global` instead of `window` to work in both frames and web
// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop.
var BrowserMutationObserver = global.MutationObserver || global.WebKitMutationObserver;
// MutationObservers are desirable because they have high priority and work
// reliably everywhere they are implemented.
// They are implemented in all modern browsers.
//
// - Android 4-4.3
// - Chrome 26-34
// - Firefox 14-29
// - Internet Explorer 11
// - iPad Safari 6-7.1
// - iPhone Safari 7-7.1
// - Safari 6-7
if (typeof BrowserMutationObserver === "function") {
requestFlush = makeRequestCallFromMutationObserver(flush);
// MessageChannels are desirable because they give direct access to the HTML
// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera
// 11-12, and in web workers in many engines.
// Although message channels yield to any queued rendering and IO tasks, they
// would be better than imposing the 4ms delay of timers.
// However, they do not work reliably in Internet Explorer or Safari.
// Internet Explorer 10 is the only browser that has setImmediate but does
// not have MutationObservers.
// Although setImmediate yields to the browser's renderer, it would be
// preferrable to falling back to setTimeout since it does not have
// the minimum 4ms penalty.
// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and
// Desktop to a lesser extent) that renders both setImmediate and
// MessageChannel useless for the purposes of ASAP.
// https://github.com/kriskowal/q/issues/396
// Timers are implemented universally.
// We fall back to timers in workers in most engines, and in foreground
// contexts in the following browsers.
// However, note that even this simple case requires nuances to operate in a
// broad spectrum of browsers.
//
// - Firefox 3-13
// - Internet Explorer 6-9
// - iPad Safari 4.3
// - Lynx 2.8.7
} else {
requestFlush = makeRequestCallFromTimer(flush);
}
// `requestFlush` requests that the high priority event queue be flushed as
// soon as possible.
// This is useful to prevent an error thrown in a task from stalling the event
// queue if the exception handled by Node.js’s
// `process.on("uncaughtException")` or by a domain.
rawAsap.requestFlush = requestFlush;
// To request a high priority event, we induce a mutation observer by toggling
// the text of a text node between "1" and "-1".
function makeRequestCallFromMutationObserver(callback) {
var toggle = 1;
var observer = new BrowserMutationObserver(callback);
var node = document.createTextNode("");
observer.observe(node, {characterData: true});
return function requestCall() {
toggle = -toggle;
node.data = toggle;
};
}
// The message channel technique was discovered by Malte Ubl and was the
// original foundation for this library.
// http://www.nonblocking.io/2011/06/windownexttick.html
// Safari 6.0.5 (at least) intermittently fails to create message ports on a
// page's first load. Thankfully, this version of Safari supports
// MutationObservers, so we don't need to fall back in that case.
// function makeRequestCallFromMessageChannel(callback) {
// var channel = new MessageChannel();
// channel.port1.onmessage = callback;
// return function requestCall() {
// channel.port2.postMessage(0);
// };
// }
// For reasons explained above, we are also unable to use `setImmediate`
// under any circumstances.
// Even if we were, there is another bug in Internet Explorer 10.
// It is not sufficient to assign `setImmediate` to `requestFlush` because
// `setImmediate` must be called *by name* and therefore must be wrapped in a
// closure.
// Never forget.
// function makeRequestCallFromSetImmediate(callback) {
// return function requestCall() {
// setImmediate(callback);
// };
// }
// Safari 6.0 has a problem where timers will get lost while the user is
// scrolling. This problem does not impact ASAP because Safari 6.0 supports
// mutation observers, so that implementation is used instead.
// However, if we ever elect to use timers in Safari, the prevalent work-around
// is to add a scroll event listener that calls for a flush.
// `setTimeout` does not call the passed callback if the delay is less than
// approximately 7 in web workers in Firefox 8 through 18, and sometimes not
// even then.
function makeRequestCallFromTimer(callback) {
return function requestCall() {
// We dispatch a timeout with a specified delay of 0 for engines that
// can reliably accommodate that request. This will usually be snapped
// to a 4 milisecond delay, but once we're flushing, there's no delay
// between events.
var timeoutHandle = setTimeout(handleTimer, 0);
// However, since this timer gets frequently dropped in Firefox
// workers, we enlist an interval handle that will try to fire
// an event 20 times per second until it succeeds.
var intervalHandle = setInterval(handleTimer, 50);
function handleTimer() {
// Whichever timer succeeds will cancel both timers and
// execute the callback.
clearTimeout(timeoutHandle);
clearInterval(intervalHandle);
callback();
}
};
}
// This is for `asap.js` only.
// Its name will be periodically randomized to break any code that depends on
// its existence.
rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer;
// ASAP was originally a nextTick shim included in Q. This was factored out
// into this ASAP package. It was later adapted to RSVP which made further
// amendments. These decisions, particularly to marginalize MessageChannel and
// to capture the MutationObserver implementation in a closure, were integrated
// back into ASAP proper.
// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],167:[function(require,module,exports){
(function (process){
"use strict";
var domain; // The domain module is executed on demand
var hasSetImmediate = typeof setImmediate === "function";
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including network IO events in Node.js.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
if (!queue.length) {
requestFlush();
flushing = true;
}
// Avoids a function call
queue[queue.length] = task;
}
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grown
// unbounded. To prevent memory excaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
while (index < queue.length) {
var currentIndex = index;
// Advance the index before calling the task. This ensures that we will
// begin flushing on the next task the task throws an error.
index = index + 1;
queue[currentIndex].call();
// Prevent leaking memory for long chains of recursive calls to `asap`.
// If we call `asap` within tasks scheduled by `asap`, the queue will
// grow, but to avoid an O(n) walk for every task we execute, we don't
// shift tasks off the queue after they have been executed.
// Instead, we periodically shift 1024 tasks off the queue.
if (index > capacity) {
// Manually shift all values starting at the index back to the
// beginning of the queue.
for (var scan = 0; scan < index; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
queue.length = 0;
index = 0;
flushing = false;
}
rawAsap.requestFlush = requestFlush;
function requestFlush() {
// Ensure flushing is not bound to any domain.
// It is not sufficient to exit the domain, because domains exist on a stack.
// To execute code outside of any domain, the following dance is necessary.
var parentDomain = process.domain;
if (parentDomain) {
if (!domain) {
// Lazy execute the domain module.
// Only employed if the user elects to use domains.
domain = require("domain");
}
domain.active = process.domain = null;
}
// `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
// cannot handle recursion.
// `requestFlush` will only be called recursively from `asap.js`, to resume
// flushing after an error is thrown into a domain.
// Conveniently, `setImmediate` was introduced in the same version
// `process.nextTick` started throwing recursion errors.
if (flushing && hasSetImmediate) {
setImmediate(flush);
} else {
process.nextTick(flush);
}
if (parentDomain) {
domain.active = process.domain = parentDomain;
}
}
}).call(this,require("FWaASH"))
},{"FWaASH":147,"domain":145}],168:[function(require,module,exports){
(function (process,global){
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
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])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Error.prototype;
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Error.prototype;
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Error.prototype;
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Error.prototype;
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Error.prototype;
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.scheduleWithState(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
}
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
!item.isCancelled() && item.invoke();
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
return currentScheduler;
}());
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle) }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { return thrower(result.e); }
}
}
}
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
runTask(event.data.substring(MSG_PREFIX.length));
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this, dt = Scheduler.normalize(dueTime);
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function(err) { o.onError(err); },
self)
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return observer.onError(ex);
}
if (currentItem.done) {
if (lastException !== null) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
if (selector) {
var selectorFn = bindCallback(selector, thisArg, 3);
}
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ToArrayObserver(observer));
};
return ToArrayObservable;
}(ObservableBase));
function ToArrayObserver(observer) {
this.observer = observer;
this.a = [];
this.isStopped = false;
}
ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
ToArrayObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
}
};
ToArrayObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onNext(this.a);
this.observer.onCompleted();
}
};
ToArrayObserver.prototype.dispose = function () { this.isStopped = true; }
ToArrayObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(null, function () {
observer.onCompleted();
});
});
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (observer) {
var sink = new FromSink(observer, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
observer = this.observer,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
try {
var next = it.next();
} catch (e) {
return observer.onError(e);
}
if (next.done) {
return observer.onCompleted();
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
return observer.onError(e);
}
}
observer.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (o) {
var first = true;
return scheduler.scheduleRecursiveWithState(initialState, function (state, self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
hasResult && (result = resultSelector(state));
} catch (e) {
return o.onError(e);
}
if (hasResult) {
o.onNext(result);
self(state);
} else {
o.onCompleted();
}
});
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
/**
* Creates an Observable sequence from changes to an array using Array.observe.
* @param {Array} array An array to observe changes.
* @returns {Observable} An observable sequence containing changes to an array from Array.observe.
*/
Observable.ofArrayChanges = function(array) {
if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); }
if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }
return new AnonymousObservable(function(observer) {
function observerFn(changes) {
for(var i = 0, len = changes.length; i < len; i++) {
observer.onNext(changes[i]);
}
}
Array.observe(array, observerFn);
return function () {
Array.unobserve(array, observerFn);
};
});
};
/**
* Creates an Observable sequence from changes to an object using Object.observe.
* @param {Object} obj An object to observe changes.
* @returns {Observable} An observable sequence containing changes to an object from Object.observe.
*/
Observable.ofObjectChanges = function(obj) {
if (obj == null) { throw new TypeError('object must not be null or undefined.'); }
if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }
return new AnonymousObservable(function(observer) {
function observerFn(changes) {
for(var i = 0, len = changes.length; i < len; i++) {
observer.onNext(changes[i]);
}
}
Object.observe(obj, observerFn);
return function () {
Object.unobserve(obj, observerFn);
};
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursiveWithState(0, function (idx, self) {
if (idx < len) {
var key = keys[idx];
observer.onNext([key, obj[key]]);
self(idx + 1);
} else {
observer.onCompleted();
}
});
});
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.count = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.count, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just' or browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (o) {
return scheduler.scheduleWithState(value, function(_,v) {
o.onNext(v);
o.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) {
try {
var result = handler(e);
} catch (ex) {
return o.onError(ex);
}
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(o));
}, function (x) { o.onCompleted(x); }));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop();
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
falseFactory = function () { return false; },
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return enumerableOf(args).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
return MergeAllObservable;
}(ObservableBase));
var MergeAllObserver = (function() {
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, g, sad) {
this.parent = parent;
this.g = g;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = observableProto.mergeObservable = function () {
return new MergeAllObservable(this);
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(o),
other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop)
);
}, source);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
*
* @example
* 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
if (typeof source === 'undefined') {
throw new Error('Source observable not found for withLatestFrom().');
}
if (typeof resultSelector !== 'function') {
throw new Error('withLatestFrom() expects a resultSelector function.');
}
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, observer.onError.bind(observer), function () {}));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var res;
var allValues = [x].concat(values);
if (!hasValueAll) return;
try {
res = resultSelector.apply(null, allValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}, observer.onError.bind(observer), function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
return observer.onError(e);
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, function (e) { observer.onError(e); }, function () { observer.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources;
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, this);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
try {
key = keySelector(value);
} catch (e) {
o.onError(e);
return;
}
}
if (hasCurrentKey) {
try {
var comparerEquals = comparer(currentKey, key);
} catch (e) {
o.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return source.subscribe(function (x) {
try {
tapObserver.onNext(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
try {
tapObserver.onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}, function () {
try {
tapObserver.onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
});
}, this);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
o.onNext(accumulation);
},
function (e) { o.onError(e); },
function () {
!hasValue && hasSeed && o.onNext(seed);
o.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
o.onNext(q);
o.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new ArgumentOutOfRangeError(); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
},
function (e) { observer.onError(e); },
function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
}
hashSet.push(key) && o.onNext(x);
},
function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [comparer] Used to determine whether the objects are equal.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) {
var source = this;
elementSelector || (elementSelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
function handleError(e) { return function (item) { item.onError(e); }; }
var map = new Dictionary(0, comparer),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
var fireNewMapEntry = false,
writer = map.tryGetValue(key);
if (!writer) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
map.remove(key) && writer.onCompleted();
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(
noop,
function (exn) {
map.getValues().forEach(handleError(exn));
observer.onError(exn);
},
expire)
);
}
var element;
try {
element = elementSelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
map.getValues().forEach(handleError(ex));
observer.onError(ex);
}, function () {
map.getValues().forEach(function (item) { item.onCompleted(); });
observer.onCompleted();
}));
return refCountDisposable;
}, source);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
var self = this;
return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg)
};
MapObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new MapObserver(observer, this.selector, this));
};
return MapObservable;
}(ObservableBase));
function MapObserver(observer, selector, source) {
this.observer = observer;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
MapObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector).call(this, x, this.i++, this.source);
if (result === errorObj) {
return this.observer.onError(result.e);
}
this.observer.onNext(result);
};
MapObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
MapObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
MapObserver.prototype.dispose = function() { this.isStopped = true; };
MapObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
o.onNext(x);
} else {
remaining--;
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining === 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new FilterObserver(observer, this.predicate, this));
};
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
var self = this;
return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg);
};
return FilterObservable;
}(ObservableBase));
function FilterObserver(observer, predicate, source) {
this.observer = observer;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
FilterObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.observer.onError(shouldYield.e);
}
shouldYield && this.observer.onNext(x);
};
FilterObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
FilterObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
FilterObserver.prototype.dispose = function() { this.isStopped = true; };
FilterObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (o) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
o.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
o.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) { list.push(x); }
}, function (e) { o.onError(e); }, function () {
o.onNext(list);
o.onCompleted();
});
}, source);
}
function firstOnly(x) {
if (x.length === 0) { throw new EmptyError(); }
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @deprecated Use #reduce instead
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var hasSeed = false, accumulator, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
return o.onError(e);
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new EmptyError());
o.onCompleted();
}
);
}, source);
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var hasSeed = false, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
return o.onError(e);
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new EmptyError());
o.onCompleted();
}
);
}, source);
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = function (predicate, thisArg) {
var source = this;
return predicate ?
source.filter(predicate, thisArg).some() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, function (e) { observer.onError(e); }, function () {
observer.onNext(false);
observer.onCompleted();
});
}, source);
};
/** @deprecated use #some instead */
observableProto.any = function () {
//deprecate('any', 'some');
return this.some.apply(this, arguments);
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = function (predicate, thisArg) {
return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not);
};
/** @deprecated use #every instead */
observableProto.all = function () {
//deprecate('all', 'every');
return this.every.apply(this, arguments);
};
/**
* Determines whether an observable sequence includes a specified element with an optional equality comparer.
* @param searchElement The value to locate in the source sequence.
* @param {Number} [fromIndex] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
*/
observableProto.includes = function (searchElement, fromIndex) {
var source = this;
function comparer(a, b) {
return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
}
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(false);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i++ >= n && comparer(x, searchElement)) {
o.onNext(true);
o.onCompleted();
}
},
function (e) { o.onError(e); },
function () {
o.onNext(false);
o.onCompleted();
});
}, this);
};
/**
* @deprecated use #includes instead.
*/
observableProto.contains = function (searchElement, fromIndex) {
//deprecate('contains', 'includes');
observableProto.includes(searchElement, fromIndex);
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.filter(predicate, thisArg).count() :
this.reduce(function (count) { return count + 1; }, 0);
};
/**
* Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.indexOf = function(searchElement, fromIndex) {
var source = this;
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(-1);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i >= n && x === searchElement) {
o.onNext(i);
o.onCompleted();
}
i++;
},
function (e) { o.onError(e); },
function () {
o.onNext(-1);
o.onCompleted();
});
}, source);
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).sum() :
this.reduce(function (prev, curr) { return prev + curr; }, 0);
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).average() :
this.reduce(function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}, {sum: 0, count: 0 }).map(function (s) {
if (s.count === 0) { throw new EmptyError(); }
return s.sum / s.count;
});
};
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
o.onError(e);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (doner) {
o.onNext(false);
o.onCompleted();
} else {
ql.push(x);
}
}, function(e) { o.onError(e); }, function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (doner) {
o.onNext(true);
o.onCompleted();
}
}
});
(isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal;
if (ql.length > 0) {
var v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
o.onError(exception);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (donel) {
o.onNext(false);
o.onCompleted();
} else {
qr.push(x);
}
}, function(e) { o.onError(e); }, function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (donel) {
o.onNext(true);
o.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
}, first);
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (o) {
var i = index;
return source.subscribe(function (x) {
if (i-- === 0) {
o.onNext(x);
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new ArgumentOutOfRangeError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
o.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate && isFunction(predicate) ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate && isFunction(predicate) ?
this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue);
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) {
o.onNext(x);
o.onCompleted();
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
var callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = callback(x, i, source);
} catch (e) {
o.onError(e);
return;
}
if (shouldRun) {
o.onNext(yieldIndex ? i : x);
o.onCompleted();
} else {
i++;
}
}, function (e) { o.onError(e); }, function () {
o.onNext(yieldIndex ? -1 : undefined);
o.onCompleted();
});
}, source);
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
if (typeof root.Set === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var s = new root.Set();
return source.subscribe(
function (x) { s.add(x); },
function (e) { o.onError(e); },
function () {
o.onNext(s);
o.onCompleted();
});
}, source);
};
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
if (typeof root.Map === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var m = new root.Map();
return source.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
o.onError(e);
return;
}
}
m.set(key, element);
},
function (e) { o.onError(e); },
function () {
o.onNext(m);
o.onCompleted();
});
}, source);
};
var fnString = 'function',
throwString = 'throw',
isObject = Rx.internals.isObject;
function toThunk(obj, ctx) {
if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); }
if (isGenerator(obj)) { return observableSpawn(obj); }
if (isObservable(obj)) { return observableToThunk(obj); }
if (isPromise(obj)) { return promiseToThunk(obj); }
if (typeof obj === fnString) { return obj; }
if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
return obj;
}
function objectToThunk(obj) {
var ctx = this;
return function (done) {
var keys = Object.keys(obj),
pending = keys.length,
results = new obj.constructor(),
finished;
if (!pending) {
timeoutScheduler.schedule(function () { done(null, results); });
return;
}
for (var i = 0, len = keys.length; i < len; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) { return; }
try {
fn = toThunk(fn, ctx);
if (typeof fn !== fnString) {
results[key] = fn;
return --pending || done(null, results);
}
fn.call(ctx, function(err, res) {
if (finished) { return; }
if (err) {
finished = true;
return done(err);
}
results[key] = res;
--pending || done(null, results);
});
} catch (e) {
finished = true;
done(e);
}
}
}
}
function observableToThunk(observable) {
return function (fn) {
var value, hasValue = false;
observable.subscribe(
function (v) {
value = v;
hasValue = true;
},
fn,
function () {
hasValue && fn(null, value);
});
}
}
function promiseToThunk(promise) {
return function(fn) {
promise.then(function(res) {
fn(null, res);
}, fn);
}
}
function isObservable(obj) {
return obj && typeof obj.subscribe === fnString;
}
function isGeneratorFunction(obj) {
return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
function isGenerator(obj) {
return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString;
}
/*
* Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions.
* @param {Function} The spawning function.
* @returns {Function} a function which has a done continuation.
*/
var observableSpawn = Rx.spawn = function (fn) {
var isGenFun = isGeneratorFunction(fn);
return function (done) {
var ctx = this,
gen = fn;
if (isGenFun) {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var len = args.length,
hasCallback = len && typeof args[len - 1] === fnString;
done = hasCallback ? args.pop() : handleError;
gen = fn.apply(this, args);
} else {
done = done || handleError;
}
next();
function exit(err, res) {
timeoutScheduler.schedule(done.bind(ctx, err, res));
}
function next(err, res) {
var ret;
// multiple args
if (arguments.length > 2) {
for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); }
}
if (err) {
try {
ret = gen[throwString](err);
} catch (e) {
return exit(e);
}
}
if (!err) {
try {
ret = gen.next(res);
} catch (e) {
return exit(e);
}
}
if (ret.done) {
return exit(null, ret.value);
}
ret.value = toThunk(ret.value, ctx);
if (typeof ret.value === fnString) {
var called = false;
try {
ret.value.call(ctx, function() {
if (called) {
return;
}
called = true;
next.apply(ctx, arguments);
});
} catch (e) {
timeoutScheduler.schedule(function () {
if (called) {
return;
}
called = true;
next.call(ctx, e);
});
}
return;
}
// Not supported
next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.'));
}
}
};
function handleError(err) {
if (!err) { return; }
timeoutScheduler.schedule(function() {
throw err;
});
}
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, context, scheduler) {
return observableToAsync(func, context, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler() {
var len = arguments.length, results = new Array(len);
for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
if (selector) {
try {
results = selector.apply(context, results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var len = arguments.length, results = [];
for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
if (selector) {
try {
results = selector.apply(context, results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette, Ember.js
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
o.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
o.onError(ex);
return;
}
o.onNext(res);
}
if (isDone && values[1]) {
o.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
o.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
o.onNext(q.shift());
}
o.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
o.onNext(q.shift());
}
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onCompleted();
else
this.queue.push(Rx.Notification.createOnCompleted());
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onError(error);
else
this.queue.push(Rx.Notification.createOnError(error));
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value));
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while ((this.queue.length >= numberOfItems && numberOfItems > 0) ||
(this.queue.length > 0 && this.queue[0].kind !== 'N')) {
var first = this.queue.shift();
first.accept(this.subject);
if (first.kind === 'N') numberOfItems--;
else { this.disposeCurrentRequest(); this.queue = []; }
}
return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0};
}
//TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function
//if (this.hasFailed) {
// this.subject.onError(this.error);
//} else if (this.hasCompleted) {
// this.subject.onCompleted();
//}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable;
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var StopAndWaitObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () { self.source.request(1); });
return this.subscription;
}
inherits(StopAndWaitObservable, __super__);
function StopAndWaitObservable (source) {
__super__.call(this, subscribe, source);
this.source = source;
}
var StopAndWaitObserver = (function (__sub__) {
inherits(StopAndWaitObserver, __sub__);
function StopAndWaitObserver (observer, observable, cancel) {
__sub__.call(this);
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
}
var stopAndWaitObserverProto = StopAndWaitObserver.prototype;
stopAndWaitObserverProto.completed = function () {
this.observer.onCompleted();
this.dispose();
};
stopAndWaitObserverProto.error = function (error) {
this.observer.onError(error);
this.dispose();
}
stopAndWaitObserverProto.next = function (value) {
this.observer.onNext(value);
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(1);
});
};
stopAndWaitObserverProto.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return StopAndWaitObserver;
}(AbstractObserver));
return StopAndWaitObservable;
}(Observable));
/**
* Attaches a stop and wait observable to the current observable.
* @returns {Observable} A stop and wait observable.
*/
ControlledObservable.prototype.stopAndWait = function () {
return new StopAndWaitObservable(this);
};
var WindowedObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () {
self.source.request(self.windowSize);
});
return this.subscription;
}
inherits(WindowedObservable, __super__);
function WindowedObservable(source, windowSize) {
__super__.call(this, subscribe, source);
this.source = source;
this.windowSize = windowSize;
}
var WindowedObserver = (function (__sub__) {
inherits(WindowedObserver, __sub__);
function WindowedObserver(observer, observable, cancel) {
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
this.received = 0;
}
var windowedObserverPrototype = WindowedObserver.prototype;
windowedObserverPrototype.completed = function () {
this.observer.onCompleted();
this.dispose();
};
windowedObserverPrototype.error = function (error) {
this.observer.onError(error);
this.dispose();
};
windowedObserverPrototype.next = function (value) {
this.observer.onNext(value);
this.received = ++this.received % this.observable.windowSize;
if (this.received === 0) {
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(self.observable.windowSize);
});
}
};
windowedObserverPrototype.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return WindowedObserver;
}(AbstractObserver));
return WindowedObservable;
}(Observable));
/**
* Creates a sliding windowed observable based upon the window size.
* @param {Number} windowSize The number of items in the window
* @returns {Observable} A windowed observable based upon the window size.
*/
ControlledObservable.prototype.windowed = function (windowSize) {
return new WindowedObservable(this, windowSize);
};
/**
* Pipes the existing Observable sequence into a Node.js Stream.
* @param {Stream} dest The destination Node.js stream.
* @returns {Stream} The destination stream.
*/
observableProto.pipe = function (dest) {
var source = this.pausableBuffered();
function onDrain() {
source.resume();
}
dest.addListener('drain', onDrain);
source.subscribe(
function (x) {
!dest.write(String(x)) && source.pause();
},
function (err) {
dest.emit('error', err);
},
function () {
// Hack check because STDIO is not closable
!dest._isStdio && dest.end();
dest.removeListener('drain', onDrain);
});
source.resume();
return dest;
};
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param windowSize [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Gets the current value or throws an exception.
* Value is frozen after onCompleted is called.
* After onError is called always throws the specified exception.
* An exception is always thrown after dispose is called.
* @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
*/
getValue: function () {
checkDisposed(this);
if (this.hasError) {
throw this.error;
}
return this.value;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
var Dictionary = (function () {
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],
noSuchkey = "no such key",
duplicatekey = "duplicate key";
function isPrime(candidate) {
if ((candidate & 1) === 0) { return candidate === 2; }
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) { return false; }
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) { return num; }
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) { return candidate; }
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) { return hash; }
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash << 5) - hash) + character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) { throw new Error(noSuchkey); }
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') { return stringHashFn(obj); }
if (typeof obj === 'number') { return numberHashFn(obj); }
if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }
if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }
if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }
if (typeof obj.valueOf === 'function') {
// Hack check for valueOf
var valueOf = obj.valueOf();
if (typeof valueOf === 'number') { return numberHashFn(valueOf); }
if (typeof valueOf === 'string') { return stringHashFn(valueOf); }
}
if (obj.hashCode) { return obj.hashCode(); }
var id = 17 * uniqueIdCounter++;
obj.hashCode = function () { return id; };
return id;
};
}());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
function Dictionary(capacity, comparer) {
if (capacity < 0) { throw new ArgumentOutOfRangeError(); }
if (capacity > 0) { this._initialize(capacity); }
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
}
var dictionaryProto = Dictionary.prototype;
dictionaryProto._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
dictionaryProto.add = function (key, value) {
this._insert(key, value, true);
};
dictionaryProto._insert = function (key, value, add) {
if (!this.buckets) { this._initialize(0); }
var index3,
num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) { throw new Error(duplicatekey); }
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
dictionaryProto._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }
for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
dictionaryProto.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length,
index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
dictionaryProto.clear = function () {
var index, len;
if (this.size <= 0) { return; }
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
dictionaryProto._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
dictionaryProto.count = function () {
return this.size - this.freeCount;
};
dictionaryProto.tryGetValue = function (key) {
var entry = this._findEntry(key);
return entry >= 0 ?
this.entries[entry].value :
undefined;
};
dictionaryProto.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
dictionaryProto.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) { return this.entries[entry].value; }
throw new Error(noSuchkey);
};
dictionaryProto.set = function (key, value) {
this._insert(key, value, false);
};
dictionaryProto.containskey = function (key) {
return this._findEntry(key) >= 0;
};
return Dictionary;
}());
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Dictionary(), rightMap = new Dictionary();
group.add(left.subscribe(
function (value) {
var id = leftId++;
var md = new SingleAssignmentDisposable();
leftMap.add(id, value);
group.add(md);
var expire = function () {
leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
rightMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(value, v);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
leftDone = true;
(rightDone || leftMap.count() === 0) && observer.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
var md = new SingleAssignmentDisposable();
rightMap.add(id, value);
group.add(md);
var expire = function () {
rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
leftMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(v, value);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
rightDone = true;
(leftDone || rightMap.count() === 0) && observer.onCompleted();
})
);
return group;
}, left);
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary(), rightMap = new Dictionary();
var leftId = 0, rightId = 0;
function handleError(e) { return function (v) { v.onError(e); }; };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.add(id, s);
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(result);
rightMap.getValues().forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
leftMap.remove(id) && s.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
observer.onCompleted.bind(observer))
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
leftMap.getValues().forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
})
);
return r;
}, left);
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
return win;
});
}
function observableWindowWithBoundaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var win = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
d.add(windowBoundaries.subscribe(function (w) {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
return r;
}, source);
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
win = new Subject();
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
function createWindowClose () {
var windowClose;
try {
windowClose = windowClosingSelector();
} catch (e) {
observer.onError(e);
return;
}
isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
var m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
createWindowClose();
}));
}
createWindowClose();
return r;
}, source);
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
return [
this.filter(predicate, thisArg),
this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
return enumerableOf(sources, resultSelector, thisArg).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
}, this);
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = [];
if (Array.isArray(arguments[0])) {
allSources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); }
}
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
}, first);
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
}, source);
};
var ChainObservable = (function (__super__) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeAll().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwError(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = root.Map || (function () {
function Map() {
this._keys = [];
this._values = [];
}
Map.prototype.get = function (key) {
var i = this._keys.indexOf(key);
return i !== -1 ? this._values[i] : undefined;
};
Map.prototype.set = function (key, value) {
var i = this._keys.indexOf(key);
i !== -1 && (this._values[i] = value);
this._values[this._keys.push(key) - 1] = value;
};
Map.prototype.forEach = function (callback, thisArg) {
for (var i = 0, len = this._keys.length; i < len; i++) {
callback.call(thisArg, this._values[i], this._keys[i]);
}
};
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
* @param other Observable sequence to match in addition to the current pattern.
* @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
return new Pattern(this.patterns.concat(other));
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
* @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
function ActivePlan(joinObserverArray, onNext, onCompleted) {
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
var joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
this.joinObservers.forEach(function (v) { v.queue.shift(); });
};
ActivePlan.prototype.match = function () {
var i, len, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
var firstValues = [],
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
var values = [];
for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
var JoinObserver = (function (__super__) {
inherits(JoinObserver, __super__);
function JoinObserver(source, onError) {
__super__.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
return this.onError(notification.exception);
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
JoinObserverPrototype.error = noop;
JoinObserverPrototype.completed = noop;
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
JoinObserverPrototype.removeActivePlan = function (activePlan) {
this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
this.activePlans.length === 0 && this.dispose();
};
JoinObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param {Function} selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var len = arguments.length, plans;
if (Array.isArray(arguments[0])) {
plans = arguments[0];
} else {
plans = new Array(len);
for(var i = 0; i < len; i++) { plans[i] = arguments[i]; }
}
return new AnonymousObservable(function (o) {
var activePlans = [],
externalSubscriptions = new Map();
var outObserver = observerCreate(
function (x) { o.onNext(x); },
function (err) {
externalSubscriptions.forEach(function (v) { v.onError(err); });
o.onError(err);
},
function (x) { o.onCompleted(); }
);
try {
for (var i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
activePlans.length === 0 && o.onCompleted();
}));
}
} catch (e) {
observableThrow(e).subscribe(o);
}
var group = new CompositeDisposable();
externalSubscriptions.forEach(function (joinObserver) {
joinObserver.subscribe();
group.add(joinObserver);
});
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count);
self(count + 1, d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
}, source);
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
* @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, this);
};
/**
* @deprecated use #debounce or #throttleWithTimeout instead.
*/
observableProto.throttle = function(dueTime, scheduler) {
//deprecate('throttle', 'debounce or throttleWithTimeout');
return this.debounce(dueTime, scheduler);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (isScheduler(timeShiftOrScheduler)) {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
if (isShift) {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
isSpan && q.shift().onCompleted();
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
},
function (e) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
observer.onError(e);
},
function () {
for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var timerD = new SerialDisposable(),
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable),
n = 0,
windowId = 0,
s = new Subject();
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
if (id !== windowId) { return; }
n = 0;
var newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(
function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
if (++n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
},
function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.map(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return { value: x, interval: span };
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) { observer.onCompleted(); }
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(start, observer.onError.bind(observer), start));
}
return new CompositeDisposable(subscription, delays);
}, this);
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false;
function setTimer(timeout) {
var myId = id;
function timerWins () {
return id === myId;
}
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
d.dispose();
}, function (e) {
timerWins() && observer.onError(e);
}, function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
}));
};
setTimer(firstTimeout);
function observerWins() {
var res = !switched;
if (res) { id++; }
return res;
}
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
}
}, function (e) {
observerWins() && observer.onError(e);
}, function () {
observerWins() && observer.onCompleted();
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
* @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounceWithSelector = function (durationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
var subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = durationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
isPromise(throttle) && (throttle = observableFromPromise(throttle));
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
hasValue && observer.onNext(value);
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, source);
};
/**
* @deprecated use #debounceWithSelector instead.
*/
observableProto.throttleWithSelector = function (durationSelector) {
//deprecate('throttleWithSelector', 'debounceWithSelector');
return this.debounceWithSelector(durationSelector);
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
o.onCompleted();
});
}, source);
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) { o.onNext(next.value); }
}
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
now - next.interval <= duration && res.push(next.value);
}
o.onNext(res);
o.onCompleted();
});
}, source);
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o));
}, source);
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
}, source);
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [scheduler]);
* @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && o.onNext(x); },
function (e) { o.onError(e); }, function () { o.onCompleted(); }));
}, source);
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} [scheduler] Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
return new CompositeDisposable(
scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }),
source.subscribe(o));
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
/**
* 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(o) {
return {
'@@transducer/init': function() {
return o;
},
'@@transducer/step': function(obs, input) {
return obs.onNext(input);
},
'@@transducer/result': function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(o) {
var xform = transducer(transformForObserver(o));
return source.subscribe(
function(v) {
try {
xform['@@transducer/step'](o, v);
} catch (e) {
o.onError(e);
}
},
function (e) { o.onError(e); },
function() { xform['@@transducer/result'](o); }
);
}, 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);
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (__super__) {
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, __super__);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
__super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); }
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (__super__) {
inherits(HistoricalScheduler, __super__);
/**
* Creates a new historical scheduler with the specified initial clock value.
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
__super__.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
var sub = tryCatch(subscribe)(ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var GroupedObservable = (function (__super__) {
inherits(GroupedObservable, __super__);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
__super__.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Used to pause and resume streams.
*/
Rx.Pauser = (function (__super__) {
inherits(Pauser, __super__);
function Pauser() {
__super__.call(this);
}
/**
* Pauses the underlying sequence.
*/
Pauser.prototype.pause = function () { this.onNext(false); };
/**
* Resumes the underlying sequence.
*/
Pauser.prototype.resume = function () { this.onNext(true); };
return Pauser;
}(Subject));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
}).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"FWaASH":147}]},{},[1]) |
app/javascript/mastodon/features/directory/index.js | yukimochi/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl } from 'react-intl';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Column from 'mastodon/components/column';
import ColumnHeader from 'mastodon/components/column_header';
import { addColumn, removeColumn, moveColumn, changeColumnParams } from 'mastodon/actions/columns';
import { fetchDirectory, expandDirectory } from 'mastodon/actions/directory';
import { List as ImmutableList } from 'immutable';
import AccountCard from './components/account_card';
import RadioButton from 'mastodon/components/radio_button';
import classNames from 'classnames';
import LoadMore from 'mastodon/components/load_more';
import ScrollContainer from 'mastodon/containers/scroll_container';
const messages = defineMessages({
title: { id: 'column.directory', defaultMessage: 'Browse profiles' },
recentlyActive: { id: 'directory.recently_active', defaultMessage: 'Recently active' },
newArrivals: { id: 'directory.new_arrivals', defaultMessage: 'New arrivals' },
local: { id: 'directory.local', defaultMessage: 'From {domain} only' },
federated: { id: 'directory.federated', defaultMessage: 'From known fediverse' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'directory', 'items'], ImmutableList()),
isLoading: state.getIn(['user_lists', 'directory', 'isLoading'], true),
domain: state.getIn(['meta', 'domain']),
});
export default @connect(mapStateToProps)
@injectIntl
class Directory extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
isLoading: PropTypes.bool,
accountIds: ImmutablePropTypes.list.isRequired,
dispatch: PropTypes.func.isRequired,
columnId: PropTypes.string,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
domain: PropTypes.string.isRequired,
params: PropTypes.shape({
order: PropTypes.string,
local: PropTypes.bool,
}),
};
state = {
order: null,
local: null,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('DIRECTORY', this.getParams(this.props, this.state)));
}
}
getParams = (props, state) => ({
order: state.order === null ? (props.params.order || 'active') : state.order,
local: state.local === null ? (props.params.local || false) : state.local,
});
handleMove = dir => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch } = this.props;
dispatch(fetchDirectory(this.getParams(this.props, this.state)));
}
componentDidUpdate (prevProps, prevState) {
const { dispatch } = this.props;
const paramsOld = this.getParams(prevProps, prevState);
const paramsNew = this.getParams(this.props, this.state);
if (paramsOld.order !== paramsNew.order || paramsOld.local !== paramsNew.local) {
dispatch(fetchDirectory(paramsNew));
}
}
setRef = c => {
this.column = c;
}
handleChangeOrder = e => {
const { dispatch, columnId } = this.props;
if (columnId) {
dispatch(changeColumnParams(columnId, ['order'], e.target.value));
} else {
this.setState({ order: e.target.value });
}
}
handleChangeLocal = e => {
const { dispatch, columnId } = this.props;
if (columnId) {
dispatch(changeColumnParams(columnId, ['local'], e.target.value === '1'));
} else {
this.setState({ local: e.target.value === '1' });
}
}
handleLoadMore = () => {
const { dispatch } = this.props;
dispatch(expandDirectory(this.getParams(this.props, this.state)));
}
render () {
const { isLoading, accountIds, intl, columnId, multiColumn, domain } = this.props;
const { order, local } = this.getParams(this.props, this.state);
const pinned = !!columnId;
const scrollableArea = (
<div className='scrollable' style={{ background: 'transparent' }}>
<div className='filter-form'>
<div className='filter-form__column' role='group'>
<RadioButton name='order' value='active' label={intl.formatMessage(messages.recentlyActive)} checked={order === 'active'} onChange={this.handleChangeOrder} />
<RadioButton name='order' value='new' label={intl.formatMessage(messages.newArrivals)} checked={order === 'new'} onChange={this.handleChangeOrder} />
</div>
<div className='filter-form__column' role='group'>
<RadioButton name='local' value='1' label={intl.formatMessage(messages.local, { domain })} checked={local} onChange={this.handleChangeLocal} />
<RadioButton name='local' value='0' label={intl.formatMessage(messages.federated)} checked={!local} onChange={this.handleChangeLocal} />
</div>
</div>
<div className={classNames('directory__list', { loading: isLoading })}>
{accountIds.map(accountId => <AccountCard id={accountId} key={accountId} />)}
</div>
<LoadMore onClick={this.handleLoadMore} visible={!isLoading} />
</div>
);
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='address-book-o'
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
/>
{multiColumn && !pinned ? <ScrollContainer scrollKey='directory'>{scrollableArea}</ScrollContainer> : scrollableArea}
</Column>
);
}
}
|
src/svg-icons/action/delete.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDelete = (props) => (
<SvgIcon {...props}>
<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
</SvgIcon>
);
ActionDelete = pure(ActionDelete);
ActionDelete.displayName = 'ActionDelete';
ActionDelete.muiName = 'SvgIcon';
export default ActionDelete;
|
app/routes/company/ShowRoute.js | ryrudnev/dss-wm | import React from 'react';
import Helmet from 'react-helmet';
import { Route } from '../../core/router';
import { Model as Company } from '../../entities/Company';
import { Deferred } from '../../util/utils';
import { PageHeader } from 'react-bootstrap';
import CompanyProfile from '../../components/CompanyProfile';
import radio from 'backbone.radio';
const router = radio.channel('router');
export default class CompanyShowRoute extends Route {
breadcrumb({ params }) {
const dfd = new Deferred;
(new Company({ fid: params.fid })).fetch({ success: model => dfd.resolve(model.get('title')) });
return dfd.promise;
}
fetch({ params }) {
this.company = new Company({ fid: params.fid });
return this.company.expandParam('waste,methods').fetch();
}
search(cb) {
this.company.searchStrategy({
success: resp => {
cb(resp.data);
},
});
}
delete(cb) {
this.company.destroy({
success: () => {
cb();
router.request('navigate', 'companies');
},
});
}
render() {
return (
<div>
<Helmet title={`Предприятие ${this.company.get('title')}`} />
<PageHeader>{`Предприятие ${this.company.get('title')}`}</PageHeader>
<CompanyProfile
company={this.company}
onSearch={cb => this.search(cb)}
onDelete={cb => this.delete(cb)}
/>
</div>
);
}
}
|
src/svg-icons/notification/event-busy.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationEventBusy = (props) => (
<SvgIcon {...props}>
<path d="M9.31 17l2.44-2.44L14.19 17l1.06-1.06-2.44-2.44 2.44-2.44L14.19 10l-2.44 2.44L9.31 10l-1.06 1.06 2.44 2.44-2.44 2.44L9.31 17zM19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11z"/>
</SvgIcon>
);
NotificationEventBusy = pure(NotificationEventBusy);
NotificationEventBusy.displayName = 'NotificationEventBusy';
NotificationEventBusy.muiName = 'SvgIcon';
export default NotificationEventBusy;
|
React_Template/node_modules/babel-plugin-transform-regenerator/node_modules/core-js/client/shim.js | rahulpnath/Blog | /**
* core-js 2.3.0
* https://github.com/zloirock/core-js
* License: http://rock.mit-license.org
* © 2016 Denis Pushkarev
*/
!function(__e, __g, undefined){
'use strict';
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1);
__webpack_require__(50);
__webpack_require__(51);
__webpack_require__(52);
__webpack_require__(54);
__webpack_require__(55);
__webpack_require__(58);
__webpack_require__(59);
__webpack_require__(60);
__webpack_require__(61);
__webpack_require__(62);
__webpack_require__(63);
__webpack_require__(64);
__webpack_require__(65);
__webpack_require__(66);
__webpack_require__(68);
__webpack_require__(70);
__webpack_require__(72);
__webpack_require__(74);
__webpack_require__(77);
__webpack_require__(78);
__webpack_require__(79);
__webpack_require__(83);
__webpack_require__(87);
__webpack_require__(88);
__webpack_require__(89);
__webpack_require__(90);
__webpack_require__(92);
__webpack_require__(93);
__webpack_require__(94);
__webpack_require__(95);
__webpack_require__(96);
__webpack_require__(98);
__webpack_require__(100);
__webpack_require__(101);
__webpack_require__(102);
__webpack_require__(104);
__webpack_require__(105);
__webpack_require__(106);
__webpack_require__(108);
__webpack_require__(109);
__webpack_require__(110);
__webpack_require__(112);
__webpack_require__(113);
__webpack_require__(114);
__webpack_require__(115);
__webpack_require__(116);
__webpack_require__(117);
__webpack_require__(118);
__webpack_require__(119);
__webpack_require__(120);
__webpack_require__(121);
__webpack_require__(122);
__webpack_require__(123);
__webpack_require__(124);
__webpack_require__(125);
__webpack_require__(127);
__webpack_require__(131);
__webpack_require__(132);
__webpack_require__(133);
__webpack_require__(134);
__webpack_require__(138);
__webpack_require__(140);
__webpack_require__(141);
__webpack_require__(142);
__webpack_require__(143);
__webpack_require__(144);
__webpack_require__(145);
__webpack_require__(146);
__webpack_require__(147);
__webpack_require__(148);
__webpack_require__(149);
__webpack_require__(150);
__webpack_require__(151);
__webpack_require__(152);
__webpack_require__(153);
__webpack_require__(159);
__webpack_require__(160);
__webpack_require__(162);
__webpack_require__(163);
__webpack_require__(164);
__webpack_require__(168);
__webpack_require__(169);
__webpack_require__(170);
__webpack_require__(171);
__webpack_require__(172);
__webpack_require__(174);
__webpack_require__(175);
__webpack_require__(176);
__webpack_require__(177);
__webpack_require__(180);
__webpack_require__(182);
__webpack_require__(183);
__webpack_require__(184);
__webpack_require__(186);
__webpack_require__(188);
__webpack_require__(190);
__webpack_require__(191);
__webpack_require__(192);
__webpack_require__(194);
__webpack_require__(195);
__webpack_require__(196);
__webpack_require__(197);
__webpack_require__(203);
__webpack_require__(206);
__webpack_require__(207);
__webpack_require__(209);
__webpack_require__(210);
__webpack_require__(211);
__webpack_require__(212);
__webpack_require__(213);
__webpack_require__(214);
__webpack_require__(215);
__webpack_require__(216);
__webpack_require__(217);
__webpack_require__(218);
__webpack_require__(219);
__webpack_require__(220);
__webpack_require__(222);
__webpack_require__(223);
__webpack_require__(224);
__webpack_require__(225);
__webpack_require__(226);
__webpack_require__(227);
__webpack_require__(228);
__webpack_require__(229);
__webpack_require__(231);
__webpack_require__(234);
__webpack_require__(235);
__webpack_require__(238);
__webpack_require__(239);
__webpack_require__(240);
__webpack_require__(241);
__webpack_require__(242);
__webpack_require__(243);
__webpack_require__(244);
__webpack_require__(245);
__webpack_require__(246);
__webpack_require__(247);
__webpack_require__(248);
__webpack_require__(250);
__webpack_require__(251);
__webpack_require__(252);
__webpack_require__(253);
__webpack_require__(254);
__webpack_require__(255);
__webpack_require__(256);
__webpack_require__(257);
__webpack_require__(259);
__webpack_require__(260);
__webpack_require__(262);
__webpack_require__(263);
__webpack_require__(264);
__webpack_require__(265);
__webpack_require__(268);
__webpack_require__(269);
__webpack_require__(270);
__webpack_require__(271);
__webpack_require__(272);
__webpack_require__(273);
__webpack_require__(274);
__webpack_require__(275);
__webpack_require__(277);
__webpack_require__(278);
__webpack_require__(279);
__webpack_require__(280);
__webpack_require__(281);
__webpack_require__(282);
__webpack_require__(283);
__webpack_require__(284);
__webpack_require__(285);
__webpack_require__(286);
__webpack_require__(287);
module.exports = __webpack_require__(288);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
var global = __webpack_require__(2)
, has = __webpack_require__(3)
, DESCRIPTORS = __webpack_require__(4)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, META = __webpack_require__(20).KEY
, $fails = __webpack_require__(5)
, shared = __webpack_require__(21)
, setToStringTag = __webpack_require__(22)
, uid = __webpack_require__(17)
, wks = __webpack_require__(23)
, wksExt = __webpack_require__(24)
, wksDefine = __webpack_require__(25)
, keyOf = __webpack_require__(27)
, enumKeys = __webpack_require__(40)
, isArray = __webpack_require__(43)
, anObject = __webpack_require__(10)
, toIObject = __webpack_require__(30)
, toPrimitive = __webpack_require__(14)
, createDesc = __webpack_require__(15)
, _create = __webpack_require__(44)
, gOPNExt = __webpack_require__(47)
, $GOPD = __webpack_require__(49)
, $DP = __webpack_require__(9)
, $keys = __webpack_require__(28)
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
var D = gOPD(it = toIObject(it), key = toPrimitive(key, true));
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]);
return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, {
configurable: true,
set: function(value){
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
}
});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(48).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(42).f = $propertyIsEnumerable;
__webpack_require__(41).f = $getOwnPropertySymbols;
if(DESCRIPTORS && !__webpack_require__(26)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(8)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ },
/* 2 */
/***/ function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ },
/* 3 */
/***/ function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(5)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 5 */
/***/ function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, core = __webpack_require__(7)
, hide = __webpack_require__(8)
, redefine = __webpack_require__(16)
, ctx = __webpack_require__(18)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target)redefine(target, key, out, type & $export.U);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ },
/* 7 */
/***/ function(module, exports) {
var core = module.exports = {version: '2.3.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9)
, createDesc = __webpack_require__(15);
module.exports = __webpack_require__(4) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(10)
, IE8_DOM_DEFINE = __webpack_require__(12)
, toPrimitive = __webpack_require__(14)
, dP = Object.defineProperty;
exports.f = __webpack_require__(4) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ },
/* 11 */
/***/ function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(4) && !__webpack_require__(5)(function(){
return Object.defineProperty(__webpack_require__(13)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, document = __webpack_require__(2).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(11);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ },
/* 15 */
/***/ function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, hide = __webpack_require__(8)
, has = __webpack_require__(3)
, SRC = __webpack_require__(17)('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
__webpack_require__(7).inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
var isFunction = typeof val == 'function';
if(isFunction)has(val, 'name') || hide(val, 'name', key);
if(O[key] === val)return;
if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if(O === global){
O[key] = val;
} else {
if(!safe){
delete O[key];
hide(O, key, val);
} else {
if(O[key])O[key] = val;
else hide(O, key, val);
}
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ },
/* 17 */
/***/ function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(19);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 19 */
/***/ function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var META = __webpack_require__(17)('meta')
, isObject = __webpack_require__(11)
, has = __webpack_require__(3)
, setDesc = __webpack_require__(9).f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !__webpack_require__(5)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
var def = __webpack_require__(9).f
, has = __webpack_require__(3)
, TAG = __webpack_require__(23)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var store = __webpack_require__(21)('wks')
, uid = __webpack_require__(17)
, Symbol = __webpack_require__(2).Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(23);
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, core = __webpack_require__(7)
, LIBRARY = __webpack_require__(26)
, wksExt = __webpack_require__(24)
, defineProperty = __webpack_require__(9).f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
/***/ },
/* 26 */
/***/ function(module, exports) {
module.exports = false;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(28)
, toIObject = __webpack_require__(30);
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(29)
, enumBugKeys = __webpack_require__(39);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var has = __webpack_require__(3)
, toIObject = __webpack_require__(30)
, arrayIndexOf = __webpack_require__(34)(false)
, IE_PROTO = __webpack_require__(38)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(31)
, defined = __webpack_require__(33);
module.exports = function(it){
return IObject(defined(it));
};
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(32);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ },
/* 32 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ },
/* 33 */
/***/ function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(30)
, toLength = __webpack_require__(35)
, toIndex = __webpack_require__(37);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(36)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ },
/* 36 */
/***/ function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(36)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var shared = __webpack_require__(21)('keys')
, uid = __webpack_require__(17);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ },
/* 39 */
/***/ function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(28)
, gOPS = __webpack_require__(41)
, pIE = __webpack_require__(42);
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
/***/ },
/* 41 */
/***/ function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ },
/* 42 */
/***/ function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(32);
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(10)
, dPs = __webpack_require__(45)
, enumBugKeys = __webpack_require__(39)
, IE_PROTO = __webpack_require__(38)('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(13)('iframe')
, i = enumBugKeys.length
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
__webpack_require__(46).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write('<script>document.F=Object</script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9)
, anObject = __webpack_require__(10)
, getKeys = __webpack_require__(28);
module.exports = __webpack_require__(4) ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(2).document && document.documentElement;
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(30)
, gOPN = __webpack_require__(48).f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(29)
, hiddenKeys = __webpack_require__(39).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(42)
, createDesc = __webpack_require__(15)
, toIObject = __webpack_require__(30)
, toPrimitive = __webpack_require__(14)
, has = __webpack_require__(3)
, IE8_DOM_DEFINE = __webpack_require__(12)
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(4) ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(4), 'Object', {defineProperty: __webpack_require__(9).f});
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !__webpack_require__(4), 'Object', {defineProperties: __webpack_require__(45)});
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(30)
, $getOwnPropertyDescriptor = __webpack_require__(49).f;
__webpack_require__(53)('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(6)
, core = __webpack_require__(7)
, fails = __webpack_require__(5);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: __webpack_require__(44)});
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(56)
, $getPrototypeOf = __webpack_require__(57);
__webpack_require__(53)('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(33);
module.exports = function(it){
return Object(defined(it));
};
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(3)
, toObject = __webpack_require__(56)
, IE_PROTO = __webpack_require__(38)('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(56)
, $keys = __webpack_require__(28);
__webpack_require__(53)('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(53)('getOwnPropertyNames', function(){
return __webpack_require__(47).f;
});
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(6);
$export($export.S + $export.F, 'Object', {assign: __webpack_require__(67)});
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(28)
, gOPS = __webpack_require__(41)
, pIE = __webpack_require__(42)
, toObject = __webpack_require__(56)
, IObject = __webpack_require__(31)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(5)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(6);
$export($export.S, 'Object', {is: __webpack_require__(69)});
/***/ },
/* 69 */
/***/ function(module, exports) {
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(6);
$export($export.S, 'Object', {setPrototypeOf: __webpack_require__(71).set});
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(11)
, anObject = __webpack_require__(10);
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = __webpack_require__(18)(Function.call, __webpack_require__(49).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = __webpack_require__(73)
, test = {};
test[__webpack_require__(23)('toStringTag')] = 'z';
if(test + '' != '[object z]'){
__webpack_require__(16)(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(32)
, TAG = __webpack_require__(23)('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = __webpack_require__(6);
$export($export.P, 'Function', {bind: __webpack_require__(75)});
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var aFunction = __webpack_require__(19)
, isObject = __webpack_require__(11)
, invoke = __webpack_require__(76)
, arraySlice = [].slice
, factories = {};
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
};
/***/ },
/* 76 */
/***/ function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9).f
, createDesc = __webpack_require__(15)
, has = __webpack_require__(3)
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
var isExtensible = Object.isExtensible || function(){
return true;
};
// 19.2.4.2 name
NAME in FProto || __webpack_require__(4) && dP(FProto, NAME, {
configurable: true,
get: function(){
try {
var that = this
, name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch(e){
return '';
}
}
});
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isObject = __webpack_require__(11)
, getPrototypeOf = __webpack_require__(57)
, HAS_INSTANCE = __webpack_require__(23)('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))__webpack_require__(9).f(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = getPrototypeOf(O))if(this.prototype === O)return true;
return false;
}});
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, has = __webpack_require__(3)
, cof = __webpack_require__(32)
, inheritIfRequired = __webpack_require__(80)
, toPrimitive = __webpack_require__(14)
, fails = __webpack_require__(5)
, gOPN = __webpack_require__(48).f
, gOPD = __webpack_require__(49).f
, dP = __webpack_require__(9).f
, $trim = __webpack_require__(81).trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof(__webpack_require__(44)(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for(var keys = __webpack_require__(4) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++){
if(has(Base, key = keys[j]) && !has($Number, key)){
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
__webpack_require__(16)(global, NUMBER, $Number);
}
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, setPrototypeOf = __webpack_require__(71).set;
module.exports = function(that, target, C){
var P, S = target.constructor;
if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
setPrototypeOf(that, P);
} return that;
};
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, defined = __webpack_require__(33)
, fails = __webpack_require__(5)
, spaces = __webpack_require__(82)
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
/***/ },
/* 82 */
/***/ function(module, exports) {
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, anInstance = __webpack_require__(84)
, toInteger = __webpack_require__(36)
, aNumberValue = __webpack_require__(85)
, repeat = __webpack_require__(86)
, $toFixed = 1..toFixed
, floor = Math.floor
, data = [0, 0, 0, 0, 0, 0]
, ERROR = 'Number.toFixed: incorrect invocation!'
, ZERO = '0';
var multiply = function(n, c){
var i = -1
, c2 = c;
while(++i < 6){
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function(n){
var i = 6
, c = 0;
while(--i >= 0){
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function(){
var i = 6
, s = '';
while(--i >= 0){
if(s !== '' || i === 0 || data[i] !== 0){
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function(x, n, acc){
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function(x){
var n = 0
, x2 = x;
while(x2 >= 4096){
n += 12;
x2 /= 4096;
}
while(x2 >= 2){
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128..toFixed(0) !== '1000000000000000128'
) || !__webpack_require__(5)(function(){
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits){
var x = aNumberValue(this, ERROR)
, f = toInteger(fractionDigits)
, s = ''
, m = ZERO
, e, z, j, k;
if(f < 0 || f > 20)throw RangeError(ERROR);
if(x != x)return 'NaN';
if(x <= -1e21 || x >= 1e21)return String(x);
if(x < 0){
s = '-';
x = -x;
}
if(x > 1e-21){
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if(e > 0){
multiply(0, z);
j = f;
while(j >= 7){
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while(j >= 23){
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if(f > 0){
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
/***/ },
/* 84 */
/***/ function(module, exports) {
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
var cof = __webpack_require__(32);
module.exports = function(it, msg){
if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
return +it;
};
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var toInteger = __webpack_require__(36)
, defined = __webpack_require__(33);
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $fails = __webpack_require__(5)
, aNumberValue = __webpack_require__(85)
, $toPrecision = 1..toPrecision;
$export($export.P + $export.F * ($fails(function(){
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function(){
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision){
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(6);
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(6)
, _isFinite = __webpack_require__(2).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(6);
$export($export.S, 'Number', {isInteger: __webpack_require__(91)});
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(11)
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(6);
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(6)
, isInteger = __webpack_require__(91)
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(6);
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(6);
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseFloat = __webpack_require__(97);
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
var $parseFloat = __webpack_require__(2).parseFloat
, $trim = __webpack_require__(81).trim;
module.exports = 1 / $parseFloat(__webpack_require__(82) + '-0') !== -Infinity ? function parseFloat(str){
var string = $trim(String(str), 3)
, result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseInt = __webpack_require__(99);
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
/***/ },
/* 99 */
/***/ function(module, exports, __webpack_require__) {
var $parseInt = __webpack_require__(2).parseInt
, $trim = __webpack_require__(81).trim
, ws = __webpack_require__(82)
, hex = /^[\-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseInt = __webpack_require__(99);
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseFloat = __webpack_require__(97);
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
/***/ },
/* 102 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.3 Math.acosh(x)
var $export = __webpack_require__(6)
, log1p = __webpack_require__(103)
, sqrt = Math.sqrt
, $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
/***/ },
/* 103 */
/***/ function(module, exports) {
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
/***/ },
/* 104 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.5 Math.asinh(x)
var $export = __webpack_require__(6)
, $asinh = Math.asinh;
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.7 Math.atanh(x)
var $export = __webpack_require__(6)
, $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
/***/ },
/* 106 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.9 Math.cbrt(x)
var $export = __webpack_require__(6)
, sign = __webpack_require__(107);
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
/***/ },
/* 107 */
/***/ function(module, exports) {
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.11 Math.clz32(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.12 Math.cosh(x)
var $export = __webpack_require__(6)
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.14 Math.expm1(x)
var $export = __webpack_require__(6)
, $expm1 = __webpack_require__(111);
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
/***/ },
/* 111 */
/***/ function(module, exports) {
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var $export = __webpack_require__(6)
, sign = __webpack_require__(107)
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = __webpack_require__(6)
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, aLen = arguments.length
, larg = 0
, arg, div;
while(i < aLen){
arg = abs(arguments[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.18 Math.imul(x, y)
var $export = __webpack_require__(6)
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * __webpack_require__(5)(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.21 Math.log10(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.20 Math.log1p(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {log1p: __webpack_require__(103)});
/***/ },
/* 117 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.22 Math.log2(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.28 Math.sign(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {sign: __webpack_require__(107)});
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.30 Math.sinh(x)
var $export = __webpack_require__(6)
, expm1 = __webpack_require__(111)
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * __webpack_require__(5)(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
/***/ },
/* 120 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.33 Math.tanh(x)
var $export = __webpack_require__(6)
, expm1 = __webpack_require__(111)
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.34 Math.trunc(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, toIndex = __webpack_require__(37)
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, aLen = arguments.length
, i = 0
, code;
while(aLen > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ },
/* 123 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, toLength = __webpack_require__(35);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, aLen = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < aLen)res.push(String(arguments[i]));
} return res.join('');
}
});
/***/ },
/* 124 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.1.3.25 String.prototype.trim()
__webpack_require__(81)('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $at = __webpack_require__(126)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(36)
, defined = __webpack_require__(33);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = __webpack_require__(6)
, toLength = __webpack_require__(35)
, context = __webpack_require__(128)
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(130)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, endPosition = arguments.length > 1 ? arguments[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(129)
, defined = __webpack_require__(33);
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(11)
, cof = __webpack_require__(32)
, MATCH = __webpack_require__(23)('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ },
/* 130 */
/***/ function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(23)('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
/***/ },
/* 131 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = __webpack_require__(6)
, context = __webpack_require__(128)
, INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(130)(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(86)
});
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = __webpack_require__(6)
, toLength = __webpack_require__(35)
, context = __webpack_require__(128)
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(130)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ },
/* 134 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $at = __webpack_require__(126)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(135)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
/***/ },
/* 135 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(26)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, hide = __webpack_require__(8)
, has = __webpack_require__(3)
, Iterators = __webpack_require__(136)
, $iterCreate = __webpack_require__(137)
, setToStringTag = __webpack_require__(22)
, getPrototypeOf = __webpack_require__(57)
, ITERATOR = __webpack_require__(23)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ },
/* 136 */
/***/ function(module, exports) {
module.exports = {};
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var create = __webpack_require__(44)
, descriptor = __webpack_require__(15)
, setToStringTag = __webpack_require__(22)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(8)(IteratorPrototype, __webpack_require__(23)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ },
/* 138 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.2 String.prototype.anchor(name)
__webpack_require__(139)('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
/***/ },
/* 139 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, fails = __webpack_require__(5)
, defined = __webpack_require__(33)
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.3 String.prototype.big()
__webpack_require__(139)('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
/***/ },
/* 141 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.4 String.prototype.blink()
__webpack_require__(139)('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
/***/ },
/* 142 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.5 String.prototype.bold()
__webpack_require__(139)('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.6 String.prototype.fixed()
__webpack_require__(139)('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
/***/ },
/* 144 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
__webpack_require__(139)('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
/***/ },
/* 145 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
__webpack_require__(139)('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
/***/ },
/* 146 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.9 String.prototype.italics()
__webpack_require__(139)('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.10 String.prototype.link(url)
__webpack_require__(139)('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
/***/ },
/* 148 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.11 String.prototype.small()
__webpack_require__(139)('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
/***/ },
/* 149 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.12 String.prototype.strike()
__webpack_require__(139)('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
/***/ },
/* 150 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.13 String.prototype.sub()
__webpack_require__(139)('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.14 String.prototype.sup()
__webpack_require__(139)('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
/***/ },
/* 152 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__(6);
$export($export.S, 'Array', {isArray: __webpack_require__(43)});
/***/ },
/* 153 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ctx = __webpack_require__(18)
, $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, call = __webpack_require__(154)
, isArrayIter = __webpack_require__(155)
, toLength = __webpack_require__(35)
, createProperty = __webpack_require__(156)
, getIterFn = __webpack_require__(157);
$export($export.S + $export.F * !__webpack_require__(158)(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ },
/* 154 */
/***/ function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(10);
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(136)
, ITERATOR = __webpack_require__(23)('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ },
/* 156 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $defineProperty = __webpack_require__(9)
, createDesc = __webpack_require__(15);
module.exports = function(object, index, value){
if(index in object)$defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(73)
, ITERATOR = __webpack_require__(23)('iterator')
, Iterators = __webpack_require__(136);
module.exports = __webpack_require__(7).getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(23)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
/***/ },
/* 159 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, createProperty = __webpack_require__(156);
// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(5)(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, aLen = arguments.length
, result = new (typeof this == 'function' ? this : Array)(aLen);
while(aLen > index)createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
/***/ },
/* 160 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (__webpack_require__(31) != Object || !__webpack_require__(161)(arrayJoin)), 'Array', {
join: function join(separator){
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
/***/ },
/* 161 */
/***/ function(module, exports, __webpack_require__) {
var fails = __webpack_require__(5);
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
/***/ },
/* 162 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, html = __webpack_require__(46)
, cof = __webpack_require__(32)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35)
, arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * __webpack_require__(5)(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
/***/ },
/* 163 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, aFunction = __webpack_require__(19)
, toObject = __webpack_require__(56)
, fails = __webpack_require__(5)
, $sort = [].sort
, test = [1, 2, 3];
$export($export.P + $export.F * (fails(function(){
// IE8-
test.sort(undefined);
}) || !fails(function(){
// V8 bug
test.sort(null);
// Old WebKit
}) || !__webpack_require__(161)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn){
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
/***/ },
/* 164 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $forEach = __webpack_require__(165)(0)
, STRICT = __webpack_require__(161)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 165 */
/***/ function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(18)
, IObject = __webpack_require__(31)
, toObject = __webpack_require__(56)
, toLength = __webpack_require__(35)
, asc = __webpack_require__(166);
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ },
/* 166 */
/***/ function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__(167);
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
/***/ },
/* 167 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, isArray = __webpack_require__(43)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
/***/ },
/* 168 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $map = __webpack_require__(165)(1);
$export($export.P + $export.F * !__webpack_require__(161)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */){
return $map(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 169 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $filter = __webpack_require__(165)(2);
$export($export.P + $export.F * !__webpack_require__(161)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 170 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $some = __webpack_require__(165)(3);
$export($export.P + $export.F * !__webpack_require__(161)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 171 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $every = __webpack_require__(165)(4);
$export($export.P + $export.F * !__webpack_require__(161)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */){
return $every(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 172 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $reduce = __webpack_require__(173);
$export($export.P + $export.F * !__webpack_require__(161)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
/***/ },
/* 173 */
/***/ function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__(19)
, toObject = __webpack_require__(56)
, IObject = __webpack_require__(31)
, toLength = __webpack_require__(35);
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
/***/ },
/* 174 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $reduce = __webpack_require__(173);
$export($export.P + $export.F * !__webpack_require__(161)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
/***/ },
/* 175 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $indexOf = __webpack_require__(34)(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(161)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
/***/ },
/* 176 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, $native = [].lastIndexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(161)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
// convert -0 to +0
if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
if(index < 0)index = length + index;
for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
return -1;
}
});
/***/ },
/* 177 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(6);
$export($export.P, 'Array', {copyWithin: __webpack_require__(178)});
__webpack_require__(179)('copyWithin');
/***/ },
/* 178 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = __webpack_require__(56)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35);
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments.length > 2 ? arguments[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ },
/* 179 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__(23)('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)__webpack_require__(8)(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ },
/* 180 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(6);
$export($export.P, 'Array', {fill: __webpack_require__(181)});
__webpack_require__(179)('fill');
/***/ },
/* 181 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = __webpack_require__(56)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35);
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, aLen = arguments.length
, index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
, end = aLen > 2 ? arguments[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
/***/ },
/* 182 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(6)
, $find = __webpack_require__(165)(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(179)(KEY);
/***/ },
/* 183 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(6)
, $find = __webpack_require__(165)(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(179)(KEY);
/***/ },
/* 184 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var addToUnscopables = __webpack_require__(179)
, step = __webpack_require__(185)
, Iterators = __webpack_require__(136)
, toIObject = __webpack_require__(30);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(135)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ },
/* 185 */
/***/ function(module, exports) {
module.exports = function(done, value){
return {value: value, done: !!done};
};
/***/ },
/* 186 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(187)('Array');
/***/ },
/* 187 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, dP = __webpack_require__(9)
, DESCRIPTORS = __webpack_require__(4)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
/***/ },
/* 188 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, inheritIfRequired = __webpack_require__(80)
, dP = __webpack_require__(9).f
, gOPN = __webpack_require__(48).f
, isRegExp = __webpack_require__(129)
, $flags = __webpack_require__(189)
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(__webpack_require__(4) && (!CORRECT_NEW || __webpack_require__(5)(function(){
re2[__webpack_require__(23)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var tiRE = this instanceof $RegExp
, piRE = isRegExp(p)
, fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function(key){
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
};
for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
__webpack_require__(16)(global, 'RegExp', $RegExp);
}
__webpack_require__(187)('RegExp');
/***/ },
/* 189 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__(10);
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
/***/ },
/* 190 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(191);
var anObject = __webpack_require__(10)
, $flags = __webpack_require__(189)
, DESCRIPTORS = __webpack_require__(4)
, TO_STRING = 'toString'
, $toString = /./[TO_STRING];
var define = function(fn){
__webpack_require__(16)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if(__webpack_require__(5)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
define(function toString(){
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if($toString.name != TO_STRING){
define(function toString(){
return $toString.call(this);
});
}
/***/ },
/* 191 */
/***/ function(module, exports, __webpack_require__) {
// 21.2.5.3 get RegExp.prototype.flags()
if(__webpack_require__(4) && /./g.flags != 'g')__webpack_require__(9).f(RegExp.prototype, 'flags', {
configurable: true,
get: __webpack_require__(189)
});
/***/ },
/* 192 */
/***/ function(module, exports, __webpack_require__) {
// @@match logic
__webpack_require__(193)('match', 1, function(defined, MATCH, $match){
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
/***/ },
/* 193 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var hide = __webpack_require__(8)
, redefine = __webpack_require__(16)
, fails = __webpack_require__(5)
, defined = __webpack_require__(33)
, wks = __webpack_require__(23);
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
/***/ },
/* 194 */
/***/ function(module, exports, __webpack_require__) {
// @@replace logic
__webpack_require__(193)('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
/***/ },
/* 195 */
/***/ function(module, exports, __webpack_require__) {
// @@search logic
__webpack_require__(193)('search', 1, function(defined, SEARCH, $search){
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
/***/ },
/* 196 */
/***/ function(module, exports, __webpack_require__) {
// @@split logic
__webpack_require__(193)('split', 2, function(defined, SPLIT, $split){
'use strict';
var isRegExp = __webpack_require__(129)
, _split = $split
, $push = [].push
, $SPLIT = 'split'
, LENGTH = 'length'
, LAST_INDEX = 'lastIndex';
if(
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
){
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function(separator, limit){
var string = String(this);
if(separator === undefined && limit === 0)return [];
// If `separator` is not a regex, use native split
if(!isRegExp(separator))return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while(match = separatorCopy.exec(string)){
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if(lastIndex > lastLastIndex){
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
});
if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if(output[LENGTH] >= splitLimit)break;
}
if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if(lastLastIndex === string[LENGTH]){
if(lastLength || !separatorCopy.test(''))output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if('0'[$SPLIT](undefined, 0)[LENGTH]){
$split = function(separator, limit){
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit){
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
/***/ },
/* 197 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(26)
, global = __webpack_require__(2)
, ctx = __webpack_require__(18)
, classof = __webpack_require__(73)
, $export = __webpack_require__(6)
, isObject = __webpack_require__(11)
, anObject = __webpack_require__(10)
, aFunction = __webpack_require__(19)
, anInstance = __webpack_require__(84)
, forOf = __webpack_require__(198)
, setProto = __webpack_require__(71).set
, speciesConstructor = __webpack_require__(199)
, task = __webpack_require__(200).set
, microtask = __webpack_require__(201)()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[__webpack_require__(23)('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(202)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
__webpack_require__(22)($Promise, PROMISE);
__webpack_require__(187)(PROMISE);
Wrapper = __webpack_require__(7)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(158)(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
/***/ },
/* 198 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(18)
, call = __webpack_require__(154)
, isArrayIter = __webpack_require__(155)
, anObject = __webpack_require__(10)
, toLength = __webpack_require__(35)
, getIterFn = __webpack_require__(157);
module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
call(iterator, f, step.value, entries);
}
};
/***/ },
/* 199 */
/***/ function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(10)
, aFunction = __webpack_require__(19)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ },
/* 200 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(18)
, invoke = __webpack_require__(76)
, html = __webpack_require__(46)
, cel = __webpack_require__(13)
, global = __webpack_require__(2)
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(__webpack_require__(32)(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ },
/* 201 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, macrotask = __webpack_require__(200).set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = __webpack_require__(32)(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
/***/ },
/* 202 */
/***/ function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(16);
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
/***/ },
/* 203 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(204);
// 23.1 Map Objects
module.exports = __webpack_require__(205)('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ },
/* 204 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var dP = __webpack_require__(9).f
, create = __webpack_require__(44)
, hide = __webpack_require__(8)
, redefineAll = __webpack_require__(202)
, ctx = __webpack_require__(18)
, anInstance = __webpack_require__(84)
, defined = __webpack_require__(33)
, forOf = __webpack_require__(198)
, $iterDefine = __webpack_require__(135)
, step = __webpack_require__(185)
, setSpecies = __webpack_require__(187)
, DESCRIPTORS = __webpack_require__(4)
, fastKey = __webpack_require__(20).fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
/***/ },
/* 205 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, redefineAll = __webpack_require__(202)
, meta = __webpack_require__(20)
, forOf = __webpack_require__(198)
, anInstance = __webpack_require__(84)
, isObject = __webpack_require__(11)
, fails = __webpack_require__(5)
, $iterDetect = __webpack_require__(158)
, setToStringTag = __webpack_require__(22)
, inheritIfRequired = __webpack_require__(80);
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO = !IS_WEAK && fails(function(){
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C()
, index = 5;
while(index--)$instance[ADDER](index, index);
return !$instance.has(-0);
});
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base, target, C);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ },
/* 206 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(204);
// 23.2 Set Objects
module.exports = __webpack_require__(205)('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ },
/* 207 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var each = __webpack_require__(165)(0)
, redefine = __webpack_require__(16)
, meta = __webpack_require__(20)
, assign = __webpack_require__(67)
, weak = __webpack_require__(208)
, isObject = __webpack_require__(11)
, has = __webpack_require__(3)
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = __webpack_require__(205)('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ },
/* 208 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var redefineAll = __webpack_require__(202)
, getWeak = __webpack_require__(20).getWeak
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11)
, anInstance = __webpack_require__(84)
, forOf = __webpack_require__(198)
, createArrayMethod = __webpack_require__(165)
, $has = __webpack_require__(3)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
/***/ },
/* 209 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var weak = __webpack_require__(208);
// 23.4 WeakSet Objects
__webpack_require__(205)('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
/***/ },
/* 210 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = __webpack_require__(6)
, _apply = Function.apply;
$export($export.S, 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
return _apply.call(target, thisArgument, argumentsList);
}
});
/***/ },
/* 211 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = __webpack_require__(6)
, create = __webpack_require__(44)
, aFunction = __webpack_require__(19)
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11)
, bind = __webpack_require__(75);
// MS Edge supports only 2 arguments
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
$export($export.S + $export.F * __webpack_require__(5)(function(){
function F(){}
return !(Reflect.construct(function(){}, [], F) instanceof F);
}), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
if(args != undefined)switch(anObject(args).length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
/***/ },
/* 212 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = __webpack_require__(9)
, $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, toPrimitive = __webpack_require__(14);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * __webpack_require__(5)(function(){
Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 213 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = __webpack_require__(6)
, gOPD = __webpack_require__(49).f
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
/***/ },
/* 214 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10);
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
__webpack_require__(137)(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
/***/ },
/* 215 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = __webpack_require__(49)
, getPrototypeOf = __webpack_require__(57)
, has = __webpack_require__(3)
, $export = __webpack_require__(6)
, isObject = __webpack_require__(11)
, anObject = __webpack_require__(10);
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
/***/ },
/* 216 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = __webpack_require__(49)
, $export = __webpack_require__(6)
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return gOPD.f(anObject(target), propertyKey);
}
});
/***/ },
/* 217 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = __webpack_require__(6)
, getProto = __webpack_require__(57)
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
/***/ },
/* 218 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.9 Reflect.has(target, propertyKey)
var $export = __webpack_require__(6);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
/***/ },
/* 219 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.10 Reflect.isExtensible(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
/***/ },
/* 220 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.11 Reflect.ownKeys(target)
var $export = __webpack_require__(6);
$export($export.S, 'Reflect', {ownKeys: __webpack_require__(221)});
/***/ },
/* 221 */
/***/ function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
var gOPN = __webpack_require__(48)
, gOPS = __webpack_require__(41)
, anObject = __webpack_require__(10)
, Reflect = __webpack_require__(2).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = gOPN.f(anObject(it))
, getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ },
/* 222 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.12 Reflect.preventExtensions(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 223 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = __webpack_require__(9)
, gOPD = __webpack_require__(49)
, getPrototypeOf = __webpack_require__(57)
, has = __webpack_require__(3)
, $export = __webpack_require__(6)
, createDesc = __webpack_require__(15)
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11);
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = gOPD.f(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
/***/ },
/* 224 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = __webpack_require__(6)
, setProto = __webpack_require__(71);
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 225 */
/***/ function(module, exports, __webpack_require__) {
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = __webpack_require__(6);
$export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
/***/ },
/* 226 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14);
$export($export.P + $export.F * __webpack_require__(5)(function(){
return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
}), 'Date', {
toJSON: function toJSON(key){
var O = toObject(this)
, pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
/***/ },
/* 227 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = __webpack_require__(6)
, fails = __webpack_require__(5)
, getTime = Date.prototype.getTime;
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
/***/ },
/* 228 */
/***/ function(module, exports, __webpack_require__) {
var DateProto = Date.prototype
, INVALID_DATE = 'Invalid Date'
, TO_STRING = 'toString'
, $toString = DateProto[TO_STRING]
, getTime = DateProto.getTime;
if(new Date(NaN) + '' != INVALID_DATE){
__webpack_require__(16)(DateProto, TO_STRING, function toString(){
var value = getTime.call(this);
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
/***/ },
/* 229 */
/***/ function(module, exports, __webpack_require__) {
var TO_PRIMITIVE = __webpack_require__(23)('toPrimitive')
, proto = Date.prototype;
if(!(TO_PRIMITIVE in proto))__webpack_require__(8)(proto, TO_PRIMITIVE, __webpack_require__(230));
/***/ },
/* 230 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var anObject = __webpack_require__(10)
, toPrimitive = __webpack_require__(14)
, NUMBER = 'number';
module.exports = function(hint){
if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
/***/ },
/* 231 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $typed = __webpack_require__(232)
, buffer = __webpack_require__(233)
, anObject = __webpack_require__(10)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35)
, isObject = __webpack_require__(11)
, TYPED_ARRAY = __webpack_require__(23)('typed_array')
, ArrayBuffer = __webpack_require__(2).ArrayBuffer
, speciesConstructor = __webpack_require__(199)
, $ArrayBuffer = buffer.ArrayBuffer
, $DataView = buffer.DataView
, $isView = $typed.ABV && ArrayBuffer.isView
, $slice = $ArrayBuffer.prototype.slice
, VIEW = $typed.VIEW
, ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it){
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * __webpack_require__(5)(function(){
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end){
if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength
, first = toIndex(start, len)
, final = toIndex(end === undefined ? len : end, len)
, result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
, viewS = new $DataView(this)
, viewT = new $DataView(result)
, index = 0;
while(first < final){
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
__webpack_require__(187)(ARRAY_BUFFER);
/***/ },
/* 232 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, hide = __webpack_require__(8)
, uid = __webpack_require__(17)
, TYPED = uid('typed_array')
, VIEW = uid('view')
, ABV = !!(global.ArrayBuffer && global.DataView)
, CONSTR = ABV
, i = 0, l = 9, Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while(i < l){
if(Typed = global[TypedArrayConstructors[i++]]){
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
/***/ },
/* 233 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, DESCRIPTORS = __webpack_require__(4)
, LIBRARY = __webpack_require__(26)
, $typed = __webpack_require__(232)
, hide = __webpack_require__(8)
, redefineAll = __webpack_require__(202)
, fails = __webpack_require__(5)
, anInstance = __webpack_require__(84)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, gOPN = __webpack_require__(48).f
, dP = __webpack_require__(9).f
, arrayFill = __webpack_require__(181)
, setToStringTag = __webpack_require__(22)
, ARRAY_BUFFER = 'ArrayBuffer'
, DATA_VIEW = 'DataView'
, PROTOTYPE = 'prototype'
, WRONG_LENGTH = 'Wrong length!'
, WRONG_INDEX = 'Wrong index!'
, $ArrayBuffer = global[ARRAY_BUFFER]
, $DataView = global[DATA_VIEW]
, Math = global.Math
, parseInt = global.parseInt
, RangeError = global.RangeError
, Infinity = global.Infinity
, BaseBuffer = $ArrayBuffer
, abs = Math.abs
, pow = Math.pow
, min = Math.min
, floor = Math.floor
, log = Math.log
, LN2 = Math.LN2
, BUFFER = 'buffer'
, BYTE_LENGTH = 'byteLength'
, BYTE_OFFSET = 'byteOffset'
, $BUFFER = DESCRIPTORS ? '_b' : BUFFER
, $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
, $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
var packIEEE754 = function(value, mLen, nBytes){
var buffer = Array(nBytes)
, eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
, i = 0
, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
, e, m, c;
value = abs(value)
if(value != value || value === Infinity){
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if(value * (c = pow(2, -e)) < 1){
e--;
c *= 2;
}
if(e + eBias >= 1){
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if(value * c >= 2){
e++;
c /= 2;
}
if(e + eBias >= eMax){
m = 0;
e = eMax;
} else if(e + eBias >= 1){
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
};
var unpackIEEE754 = function(buffer, mLen, nBytes){
var eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, nBits = eLen - 7
, i = nBytes - 1
, s = buffer[i--]
, e = s & 127
, m;
s >>= 7;
for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if(e === 0){
e = 1 - eBias;
} else if(e === eMax){
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
};
var unpackI32 = function(bytes){
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
};
var packI8 = function(it){
return [it & 0xff];
};
var packI16 = function(it){
return [it & 0xff, it >> 8 & 0xff];
};
var packI32 = function(it){
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
};
var packF64 = function(it){
return packIEEE754(it, 52, 8);
};
var packF32 = function(it){
return packIEEE754(it, 23, 4);
};
var addGetter = function(C, key, internal){
dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
};
var get = function(view, bytes, index, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
};
var set = function(view, bytes, index, conversion, value, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = conversion(+value);
for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
};
var validateArrayBufferArguments = function(that, length){
anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
var numberLength = +length
, byteLength = toLength(numberLength);
if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
return byteLength;
};
if(!$typed.ABV){
$ArrayBuffer = function ArrayBuffer(length){
var byteLength = validateArrayBufferArguments(this, length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength){
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH]
, offset = toInteger(byteOffset);
if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if(DESCRIPTORS){
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset){
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset){
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if(!fails(function(){
new $ArrayBuffer; // eslint-disable-line no-new
}) || !fails(function(){
new $ArrayBuffer(.5); // eslint-disable-line no-new
})){
$ArrayBuffer = function ArrayBuffer(length){
return new BaseBuffer(validateArrayBufferArguments(this, length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
};
if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2))
, $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
/***/ },
/* 234 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
$export($export.G + $export.W + $export.F * !__webpack_require__(232).ABV, {
DataView: __webpack_require__(233).DataView
});
/***/ },
/* 235 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int8', 1, function(init){
return function Int8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 236 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
if(__webpack_require__(4)){
var LIBRARY = __webpack_require__(26)
, global = __webpack_require__(2)
, fails = __webpack_require__(5)
, $export = __webpack_require__(6)
, $typed = __webpack_require__(232)
, $buffer = __webpack_require__(233)
, ctx = __webpack_require__(18)
, anInstance = __webpack_require__(84)
, propertyDesc = __webpack_require__(15)
, hide = __webpack_require__(8)
, redefineAll = __webpack_require__(202)
, isInteger = __webpack_require__(91)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, toIndex = __webpack_require__(37)
, toPrimitive = __webpack_require__(14)
, has = __webpack_require__(3)
, same = __webpack_require__(69)
, classof = __webpack_require__(73)
, isObject = __webpack_require__(11)
, toObject = __webpack_require__(56)
, isArrayIter = __webpack_require__(155)
, create = __webpack_require__(44)
, getPrototypeOf = __webpack_require__(57)
, gOPN = __webpack_require__(48).f
, isIterable = __webpack_require__(237)
, getIterFn = __webpack_require__(157)
, uid = __webpack_require__(17)
, wks = __webpack_require__(23)
, createArrayMethod = __webpack_require__(165)
, createArrayIncludes = __webpack_require__(34)
, speciesConstructor = __webpack_require__(199)
, ArrayIterators = __webpack_require__(184)
, Iterators = __webpack_require__(136)
, $iterDetect = __webpack_require__(158)
, setSpecies = __webpack_require__(187)
, arrayFill = __webpack_require__(181)
, arrayCopyWithin = __webpack_require__(178)
, $DP = __webpack_require__(9)
, $GOPD = __webpack_require__(49)
, dP = $DP.f
, gOPD = $GOPD.f
, RangeError = global.RangeError
, TypeError = global.TypeError
, Uint8Array = global.Uint8Array
, ARRAY_BUFFER = 'ArrayBuffer'
, SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
, BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
, PROTOTYPE = 'prototype'
, ArrayProto = Array[PROTOTYPE]
, $ArrayBuffer = $buffer.ArrayBuffer
, $DataView = $buffer.DataView
, arrayForEach = createArrayMethod(0)
, arrayFilter = createArrayMethod(2)
, arraySome = createArrayMethod(3)
, arrayEvery = createArrayMethod(4)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, arrayIncludes = createArrayIncludes(true)
, arrayIndexOf = createArrayIncludes(false)
, arrayValues = ArrayIterators.values
, arrayKeys = ArrayIterators.keys
, arrayEntries = ArrayIterators.entries
, arrayLastIndexOf = ArrayProto.lastIndexOf
, arrayReduce = ArrayProto.reduce
, arrayReduceRight = ArrayProto.reduceRight
, arrayJoin = ArrayProto.join
, arraySort = ArrayProto.sort
, arraySlice = ArrayProto.slice
, arrayToString = ArrayProto.toString
, arrayToLocaleString = ArrayProto.toLocaleString
, ITERATOR = wks('iterator')
, TAG = wks('toStringTag')
, TYPED_CONSTRUCTOR = uid('typed_constructor')
, DEF_CONSTRUCTOR = uid('def_constructor')
, ALL_CONSTRUCTORS = $typed.CONSTR
, TYPED_ARRAY = $typed.TYPED
, VIEW = $typed.VIEW
, WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function(O, length){
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function(){
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
new Uint8Array(1).set({});
});
var strictToLength = function(it, SAME){
if(it === undefined)throw TypeError(WRONG_LENGTH);
var number = +it
, length = toLength(it);
if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
return length;
};
var toOffset = function(it, BYTES){
var offset = toInteger(it);
if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
return offset;
};
var validate = function(it){
if(isObject(it) && TYPED_ARRAY in it)return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function(C, length){
if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function(O, list){
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function(C, list){
var index = 0
, length = list.length
, result = allocate(C, length);
while(length > index)result[index] = list[index++];
return result;
};
var addGetter = function(it, key, internal){
dP(it, key, {get: function(){ return this._d[internal]; }});
};
var $from = function from(source /*, mapfn, thisArg */){
var O = toObject(source)
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, iterFn = getIterFn(O)
, i, length, values, result, step, iterator;
if(iterFn != undefined && !isArrayIter(iterFn)){
for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
values.push(step.value);
} O = values;
}
if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/*...items*/){
var index = 0
, length = arguments.length
, result = allocate(this, length);
while(length > index)result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString(){
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /*, end */){
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /*, thisArg */){
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /*, thisArg */){
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /*, thisArg */){
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /*, thisArg */){
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /*, thisArg */){
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /*, fromIndex */){
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /*, fromIndex */){
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator){ // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /*, thisArg */){
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse(){
var that = this
, length = validate(that).length
, middle = Math.floor(length / 2)
, index = 0
, value;
while(index < middle){
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /*, thisArg */){
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn){
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end){
var O = validate(this)
, length = O.length
, $begin = toIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end){
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /*, offset */){
validate(this);
var offset = toOffset(arguments[1], 1)
, length = this.length
, src = toObject(arrayLike)
, len = toLength(src.length)
, index = 0;
if(len + offset > length)throw RangeError(WRONG_LENGTH);
while(index < len)this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries(){
return arrayEntries.call(validate(this));
},
keys: function keys(){
return arrayKeys.call(validate(this));
},
values: function values(){
return arrayValues.call(validate(this));
}
};
var isTAIndex = function(target, key){
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key){
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc){
if(isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
){
target[key] = desc.value;
return target;
} else return dP(target, key, desc);
};
if(!ALL_CONSTRUCTORS){
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if(fails(function(){ arrayToString.call({}); })){
arrayToString = arrayToLocaleString = function toString(){
return arrayJoin.call(this);
}
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function(){ /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function(){ return this[TYPED_ARRAY]; }
});
module.exports = function(KEY, BYTES, wrapper, CLAMPED){
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
, ISNT_UINT8 = NAME != 'Uint8Array'
, GETTER = 'get' + KEY
, SETTER = 'set' + KEY
, TypedArray = global[NAME]
, Base = TypedArray || {}
, TAC = TypedArray && getPrototypeOf(TypedArray)
, FORCED = !TypedArray || !$typed.ABV
, O = {}
, TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function(that, index){
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function(that, index, value){
var data = that._d;
if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function(that, index){
dP(that, index, {
get: function(){
return getter(this, index);
},
set: function(value){
return setter(this, index, value);
},
enumerable: true
});
};
if(FORCED){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME, '_d');
var index = 0
, offset = 0
, buffer, byteLength, length, klass;
if(!isObject(data)){
length = strictToLength(data, true)
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if($length === undefined){
if($len % BYTES)throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if(byteLength < 0)throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if(TYPED_ARRAY in data){
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while(index < length)addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if(!$iterDetect(function(iter){
// V8 works with iterators, but fails in many other cases
// https://code.google.com/p/v8/issues/detail?id=4552
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if(TYPED_ARRAY in data)return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR]
, CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
, $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
dP(TypedArrayPrototype, TAG, {
get: function(){ return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES,
from: $from,
of: $of
});
if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
$export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
$export($export.P + $export.F * fails(function(){
new TypedArray(1).slice();
}), NAME, {slice: $slice});
$export($export.P + $export.F * (fails(function(){
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
}) || !fails(function(){
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, {toLocaleString: $toLocaleString});
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function(){ /* empty */ };
/***/ },
/* 237 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(73)
, ITERATOR = __webpack_require__(23)('iterator')
, Iterators = __webpack_require__(136);
module.exports = __webpack_require__(7).isIterable = function(it){
var O = Object(it);
return O[ITERATOR] !== undefined
|| '@@iterator' in O
|| Iterators.hasOwnProperty(classof(O));
};
/***/ },
/* 238 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint8', 1, function(init){
return function Uint8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 239 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint8', 1, function(init){
return function Uint8ClampedArray(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
}, true);
/***/ },
/* 240 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int16', 2, function(init){
return function Int16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 241 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint16', 2, function(init){
return function Uint16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 242 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int32', 4, function(init){
return function Int32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 243 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint32', 4, function(init){
return function Uint32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 244 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Float32', 4, function(init){
return function Float32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 245 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Float64', 8, function(init){
return function Float64Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 246 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__(6)
, $includes = __webpack_require__(34)(true);
$export($export.P, 'Array', {
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(179)('includes');
/***/ },
/* 247 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = __webpack_require__(6)
, $at = __webpack_require__(126)(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
/***/ },
/* 248 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(6)
, $pad = __webpack_require__(249);
$export($export.P, 'String', {
padStart: function padStart(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
/***/ },
/* 249 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = __webpack_require__(35)
, repeat = __webpack_require__(86)
, defined = __webpack_require__(33);
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength || fillStr == '')return S;
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
/***/ },
/* 250 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(6)
, $pad = __webpack_require__(249);
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
/***/ },
/* 251 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(81)('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
}, 'trimStart');
/***/ },
/* 252 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(81)('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
/***/ },
/* 253 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = __webpack_require__(6)
, defined = __webpack_require__(33)
, toLength = __webpack_require__(35)
, isRegExp = __webpack_require__(129)
, getFlags = __webpack_require__(189)
, RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function(regexp, string){
this._r = regexp;
this._s = string;
};
__webpack_require__(137)($RegExpStringIterator, 'RegExp String', function next(){
var match = this._r.exec(this._s);
return {value: match, done: match === null};
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp){
defined(this);
if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!');
var S = String(this)
, flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp)
, rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
/***/ },
/* 254 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(25)('asyncIterator');
/***/ },
/* 255 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(25)('observable');
/***/ },
/* 256 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = __webpack_require__(6)
, ownKeys = __webpack_require__(221)
, toIObject = __webpack_require__(30)
, gOPD = __webpack_require__(49)
, createProperty = __webpack_require__(156);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, getDesc = gOPD.f
, keys = ownKeys(O)
, result = {}
, i = 0
, key, D;
while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key));
return result;
}
});
/***/ },
/* 257 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(6)
, $values = __webpack_require__(258)(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
/***/ },
/* 258 */
/***/ function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(28)
, toIObject = __webpack_require__(30)
, isEnum = __webpack_require__(42).f;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
/***/ },
/* 259 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(6)
, $entries = __webpack_require__(258)(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
/***/ },
/* 260 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, aFunction = __webpack_require__(19)
, $defineProperty = __webpack_require__(9);
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
__webpack_require__(4) && $export($export.P + __webpack_require__(261), 'Object', {
__defineGetter__: function __defineGetter__(P, getter){
$defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true});
}
});
/***/ },
/* 261 */
/***/ function(module, exports, __webpack_require__) {
// Forced replacement prototype accessors methods
module.exports = __webpack_require__(26)|| !__webpack_require__(5)(function(){
var K = Math.random();
// In FF throws only define methods
__defineSetter__.call(null, K, function(){ /* empty */});
delete __webpack_require__(2)[K];
});
/***/ },
/* 262 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, aFunction = __webpack_require__(19)
, $defineProperty = __webpack_require__(9);
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
__webpack_require__(4) && $export($export.P + __webpack_require__(261), 'Object', {
__defineSetter__: function __defineSetter__(P, setter){
$defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true});
}
});
/***/ },
/* 263 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14)
, getPrototypeOf = __webpack_require__(57)
, getOwnPropertyDescriptor = __webpack_require__(49).f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
__webpack_require__(4) && $export($export.P + __webpack_require__(261), 'Object', {
__lookupGetter__: function __lookupGetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.get;
} while(O = getPrototypeOf(O));
}
});
/***/ },
/* 264 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14)
, getPrototypeOf = __webpack_require__(57)
, getOwnPropertyDescriptor = __webpack_require__(49).f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
__webpack_require__(4) && $export($export.P + __webpack_require__(261), 'Object', {
__lookupSetter__: function __lookupSetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.set;
} while(O = getPrototypeOf(O));
}
});
/***/ },
/* 265 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(6);
$export($export.P + $export.R, 'Map', {toJSON: __webpack_require__(266)('Map')});
/***/ },
/* 266 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = __webpack_require__(73)
, from = __webpack_require__(267);
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
/***/ },
/* 267 */
/***/ function(module, exports, __webpack_require__) {
var forOf = __webpack_require__(198);
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
/***/ },
/* 268 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(6);
$export($export.P + $export.R, 'Set', {toJSON: __webpack_require__(266)('Set')});
/***/ },
/* 269 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-global
var $export = __webpack_require__(6);
$export($export.S, 'System', {global: __webpack_require__(2)});
/***/ },
/* 270 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-is-error
var $export = __webpack_require__(6)
, cof = __webpack_require__(32);
$export($export.S, 'Error', {
isError: function isError(it){
return cof(it) === 'Error';
}
});
/***/ },
/* 271 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
/***/ },
/* 272 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
/***/ },
/* 273 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
imulh: function imulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >> 16
, v1 = $v >> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
/***/ },
/* 274 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
umulh: function umulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >>> 16
, v1 = $v >>> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
/***/ },
/* 275 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
}});
/***/ },
/* 276 */
/***/ function(module, exports, __webpack_require__) {
var Map = __webpack_require__(203)
, $export = __webpack_require__(6)
, shared = __webpack_require__(21)('metadata')
, store = shared.store || (shared.store = new (__webpack_require__(207)));
var getOrCreateMetadataMap = function(target, targetKey, create){
var targetMetadata = store.get(target);
if(!targetMetadata){
if(!create)return undefined;
store.set(target, targetMetadata = new Map);
}
var keyMetadata = targetMetadata.get(targetKey);
if(!keyMetadata){
if(!create)return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map);
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function(target, targetKey){
var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
, keys = [];
if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
return keys;
};
var toMetaKey = function(it){
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function(O){
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
/***/ },
/* 277 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, toMetaKey = metadata.key
, getOrCreateMetadataMap = metadata.map
, store = metadata.store;
metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
, metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
if(metadataMap.size)return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
}});
/***/ },
/* 278 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 279 */
/***/ function(module, exports, __webpack_require__) {
var Set = __webpack_require__(206)
, from = __webpack_require__(267)
, metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
var ordinaryMetadataKeys = function(O, P){
var oKeys = ordinaryOwnMetadataKeys(O, P)
, parent = getPrototypeOf(O);
if(parent === null)return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
/***/ },
/* 280 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 281 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
/***/ },
/* 282 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
var ordinaryHasMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 283 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 284 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, aFunction = __webpack_require__(19)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({metadata: function metadata(metadataKey, metadataValue){
return function decorator(target, targetKey){
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
}});
/***/ },
/* 285 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = __webpack_require__(6)
, microtask = __webpack_require__(201)()
, process = __webpack_require__(2).process
, isNode = __webpack_require__(32)(process) == 'process';
$export($export.G, {
asap: function asap(fn){
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
/***/ },
/* 286 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $task = __webpack_require__(200);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
/***/ },
/* 287 */
/***/ function(module, exports, __webpack_require__) {
var $iterators = __webpack_require__(184)
, redefine = __webpack_require__(16)
, global = __webpack_require__(2)
, hide = __webpack_require__(8)
, Iterators = __webpack_require__(136)
, wks = __webpack_require__(23)
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true);
}
}
/***/ },
/* 288 */
/***/ function(module, exports, __webpack_require__) {
// ie9- setTimeout & setInterval additional parameters fix
var global = __webpack_require__(2)
, $export = __webpack_require__(6)
, invoke = __webpack_require__(76)
, partial = __webpack_require__(289)
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
/***/ },
/* 289 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var path = __webpack_require__(290)
, invoke = __webpack_require__(76)
, aFunction = __webpack_require__(19);
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, aLen = arguments.length
, j = 0, k = 0, args;
if(!holder && !aLen)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
while(aLen > k)args.push(arguments[k++]);
return invoke(fn, args, that);
};
};
/***/ },
/* 290 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(2);
/***/ }
/******/ ]);
// CommonJS export
if(typeof module != 'undefined' && module.exports)module.exports = __e;
// RequireJS export
else if(typeof define == 'function' && define.amd)define(function(){return __e});
// Export to global object
else __g.core = __e;
}(1, 1); |
ajax/libs/react-native-web/0.14.3/exports/RefreshControl/index.js | cdnjs/cdnjs | function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import View from '../View';
import React from 'react';
function RefreshControl(props) {
var colors = props.colors,
enabled = props.enabled,
onRefresh = props.onRefresh,
progressBackgroundColor = props.progressBackgroundColor,
progressViewOffset = props.progressViewOffset,
refreshing = props.refreshing,
size = props.size,
tintColor = props.tintColor,
title = props.title,
titleColor = props.titleColor,
rest = _objectWithoutPropertiesLoose(props, ["colors", "enabled", "onRefresh", "progressBackgroundColor", "progressViewOffset", "refreshing", "size", "tintColor", "title", "titleColor"]);
return React.createElement(View, rest);
}
export default RefreshControl; |
docs/components/Logo/Logo.js | kradio3/react-mdc-web | import React from 'react';
import logoUrl from './logo-white-30.svg';
const Logo = () => (
<img
className='toolbar-logo'
src={logoUrl}
/>
);
export default Logo;
|
src/entries/app.js | dingzhang/OpenDay | import './app.less';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import routes from '../routes/route';
import configureStore from '../store/configureStore';
import { syncHistoryWithStore } from 'react-router-redux';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>, document.getElementById('root')
); |
src/svg-icons/av/video-call.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVideoCall = (props) => (
<SvgIcon {...props}>
<path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4zM14 13h-3v3H9v-3H6v-2h3V8h2v3h3v2z"/>
</SvgIcon>
);
AvVideoCall = pure(AvVideoCall);
AvVideoCall.displayName = 'AvVideoCall';
AvVideoCall.muiName = 'SvgIcon';
export default AvVideoCall;
|
popup/component/extractions.js | ethcore/parity-extension | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import { h, Component } from 'preact';
import { bind } from 'decko';
import AccountCard from '../../content/components/accountCard';
import styles from './extractions.css';
class Account extends Component {
state = {
badges: [],
small: true,
tokens: []
};
componentWillMount () {
const { account, store } = this.props;
const { badges, tokens } = account;
return store.augmentor.fetchImages({ badges, tokens })
.then(([ badges, tokens ]) => {
this.setState({ badges, tokens });
});
}
render () {
const { account } = this.props;
const { badges, small, tokens } = this.state;
const { address, email, name, size } = account;
return (
<div
className={ styles.accountCard }
onClick={ this.toggle }
>
<AccountCard
address={ address }
badges={ badges }
email={ email }
key={ address }
name={ name }
safe
size={ size }
small={ small }
tokens={ tokens }
/>
</div>
);
}
@bind
toggle () {
const { small } = this.state;
this.setState({ small: !small });
}
}
export default class Extractions extends Component {
render () {
const { extractions, store } = this.props;
if (!extractions || extractions.length === 0) {
return (
<p>No identities have been found on the page.</p>
);
}
return (
<div className={ styles.extractions }>
{ this.renderDesc(extractions.length) }
<div className={ styles.accounts }>
{ this.renderAccounts(extractions, store) }
</div>
</div>
);
}
renderDesc (n) {
if (n > 1) {
return (
<p>{ n } identities have been found</p>
);
}
return (
<p>{ n } identity has been found</p>
);
}
renderAccounts (accounts, store) {
return accounts.map((account) => {
return (
<Account
account={ account }
store={ store }
/>
);
});
}
}
|
node_modules/babel-plugin-react-require/built-examples/stateless-component1.js | esteladiaz/esteladiaz.github.io | import React from "react";
function Component1() {
return <div />;
} |
vendor/ember-data/ember-data.js | kharmabum/ft-starter | /*!
* @overview Ember Data
* @copyright Copyright 2011-2014 Tilde Inc. and contributors.
* Portions Copyright 2011 LivingSocial Inc.
* @license Licensed under MIT license (see license.js)
* @version 1.0.0-beta.7+canary.b45e23ba
*/
(function(global) {
var define, requireModule, require, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = require = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
define("activemodel-adapter/lib/initializers",
["../../ember-data/lib/system/container_proxy","./system/active_model_serializer","./system/active_model_adapter"],
function(__dependency1__, __dependency2__, __dependency3__) {
"use strict";
var ContainerProxy = __dependency1__["default"];
var ActiveModelSerializer = __dependency2__["default"];
var ActiveModelAdapter = __dependency3__["default"];
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "activeModelAdapter",
initialize: function(container, application) {
var proxy = new ContainerProxy(container);
proxy.registerDeprecations([
{deprecated: 'serializer:_ams', valid: 'serializer:-active-model'},
{deprecated: 'adapter:_ams', valid: 'adapter:-active-model'}
]);
application.register('serializer:-active-model', ActiveModelSerializer);
application.register('adapter:-active-model', ActiveModelAdapter);
}
});
});
});
define("activemodel-adapter/lib/main",
["./system","./initializers","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var ActiveModelAdapter = __dependency1__.ActiveModelAdapter;
var ActiveModelSerializer = __dependency1__.ActiveModelSerializer;
var EmbeddedRecordsMixin = __dependency1__.EmbeddedRecordsMixin;
__exports__.ActiveModelAdapter = ActiveModelAdapter;
__exports__.ActiveModelSerializer = ActiveModelSerializer;
__exports__.EmbeddedRecordsMixin = EmbeddedRecordsMixin;
});
define("activemodel-adapter/lib/system",
["./system/embedded_records_mixin","./system/active_model_adapter","./system/active_model_serializer","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var EmbeddedRecordsMixin = __dependency1__["default"];
var ActiveModelAdapter = __dependency2__["default"];
var ActiveModelSerializer = __dependency3__["default"];
__exports__.EmbeddedRecordsMixin = EmbeddedRecordsMixin;
__exports__.ActiveModelAdapter = ActiveModelAdapter;
__exports__.ActiveModelSerializer = ActiveModelSerializer;
});
define("activemodel-adapter/lib/system/active_model_adapter",
["../../../ember-data/lib/adapters","../../../ember-data/lib/system/adapter","../../../ember-inflector/lib/main","./active_model_serializer","./embedded_records_mixin","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) {
"use strict";
var RESTAdapter = __dependency1__.RESTAdapter;
var InvalidError = __dependency2__.InvalidError;
var pluralize = __dependency3__.pluralize;
var ActiveModelSerializer = __dependency4__["default"];
var EmbeddedRecordsMixin = __dependency5__["default"];
/**
@module ember-data
*/
var forEach = Ember.EnumerableUtils.forEach;
var decamelize = Ember.String.decamelize,
underscore = Ember.String.underscore;
/**
The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate
with a JSON API that uses an underscored naming convention instead of camelcasing.
It has been designed to work out of the box with the
[active_model_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem.
This adapter extends the DS.RESTAdapter by making consistent use of the camelization,
decamelization and pluralization methods to normalize the serialized JSON into a
format that is compatible with a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelAdapter expects the JSON returned from your server to follow
the REST adapter conventions substituting underscored keys for camelcased ones.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
@class ActiveModelAdapter
@constructor
@namespace DS
@extends DS.Adapter
**/
var ActiveModelAdapter = RESTAdapter.extend({
defaultSerializer: '-active-model',
/**
The ActiveModelAdapter overrides the `pathForType` method to build
underscored URLs by decamelizing and pluralizing the object type name.
```js
this.pathForType("famousPerson");
//=> "famous_people"
```
@method pathForType
@param {String} type
@returns String
*/
pathForType: function(type) {
var decamelized = decamelize(type);
var underscored = underscore(decamelized);
return pluralize(underscored);
},
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
A 422 HTTP response from the server generally implies that the request
was well formed but the API was unable to process it because the
content was not semantically correct or meaningful per the API.
For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918
https://tools.ietf.org/html/rfc4918#section-11.2
@method ajaxError
@param jqXHR
@returns error
*/
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var response = Ember.$.parseJSON(jqXHR.responseText),
errors = {};
if (response.errors !== undefined) {
var jsonErrors = response.errors;
forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
}
return new InvalidError(errors);
} else {
return error;
}
}
});
__exports__["default"] = ActiveModelAdapter;
});
define("activemodel-adapter/lib/system/active_model_serializer",
["../../../ember-inflector/lib/main","../../../ember-data/lib/serializers/rest_serializer","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var singularize = __dependency1__.singularize;
var RESTSerializer = __dependency2__["default"];
/**
@module ember-data
*/
var get = Ember.get,
forEach = Ember.EnumerableUtils.forEach,
camelize = Ember.String.camelize,
capitalize = Ember.String.capitalize,
decamelize = Ember.String.decamelize,
underscore = Ember.String.underscore;
var ActiveModelSerializer = RESTSerializer.extend({
// SERIALIZE
/**
Converts camelcased attributes to underscored when serializing.
@method keyForAttribute
@param {String} attribute
@returns String
*/
keyForAttribute: function(attr) {
return decamelize(attr);
},
/**
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} key
@param {String} kind
@returns String
*/
keyForRelationship: function(key, kind) {
key = decamelize(key);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return singularize(key) + "_ids";
} else {
return key;
}
},
/**
Does not serialize hasMany relationships by default.
*/
serializeHasMany: Ember.K,
/**
Underscores the JSON root keys when serializing.
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(data, type, record, options) {
var root = underscore(decamelize(type.typeKey));
data[root] = this.serialize(record, options);
},
/**
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute(key);
json[key + "_type"] = capitalize(camelize(belongsTo.constructor.typeKey));
},
// EXTRACT
/**
Extracts the model typeKey from underscored root objects.
@method typeForRoot
@param {String} root
@returns String the model's typeKey
*/
typeForRoot: function(root) {
var camelized = camelize(root);
return singularize(camelized);
},
/**
Add extra step to `DS.RESTSerializer.normalize` so links are
normalized.
If your payload looks like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flagged_comments": "api/comments/flagged" }
}
}
```
The normalized version would look like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flaggedComments": "api/comments/flagged" }
}
}
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@returns Object
*/
normalize: function(type, hash, prop) {
this.normalizeLinks(hash);
return this._super(type, hash, prop);
},
/**
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} hash
*/
normalizeLinks: function(data){
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
},
/**
Normalize the polymorphic type from the JSON.
Normalize:
```js
{
id: "1"
minion: { type: "evil_minion", id: "12"}
}
```
To:
```js
{
id: "1"
minion: { type: "evilMinion", id: "12"}
}
```
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey, payload;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
if (relationship.options.polymorphic) {
payloadKey = this.keyForAttribute(key);
payload = hash[payloadKey];
if (payload && payload.type) {
payload.type = this.typeForRoot(payload.type);
} else if (payload && relationship.kind === "hasMany") {
var self = this;
forEach(payload, function(single) {
single.type = self.typeForRoot(single.type);
});
}
} else {
payloadKey = this.keyForRelationship(key, relationship.kind);
payload = hash[payloadKey];
}
hash[key] = payload;
if (key !== payloadKey) {
delete hash[payloadKey];
}
}, this);
}
}
});
__exports__["default"] = ActiveModelSerializer;
});
define("activemodel-adapter/lib/system/embedded_records_mixin",
["../../../ember-inflector/lib/main","exports"],
function(__dependency1__, __exports__) {
"use strict";
var get = Ember.get;
var forEach = Ember.EnumerableUtils.forEach;
var pluralize = __dependency1__.pluralize;
/**
The EmbeddedRecordsMixin allows you to add embedded record support to your
serializers.
To set up embedded records, you include the mixin into the serializer and then
define your embedded relations.
```js
App.PostSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
})
```
Currently only `{embedded: 'always'}` records are supported.
@class EmbeddedRecordsMixin
@namespace DS
*/
var EmbeddedRecordsMixin = Ember.Mixin.create({
/**
Serialize has-may relationship when it is configured as embedded objects.
@method serializeHasMany
*/
serializeHasMany: function(record, json, relationship) {
var key = relationship.key,
attrs = get(this, 'attrs'),
embed = attrs && attrs[key] && attrs[key].embedded === 'always';
if (embed) {
json[this.keyForAttribute(key)] = get(record, key).map(function(relation) {
var data = relation.serialize(),
primaryKey = get(this, 'primaryKey');
data[primaryKey] = get(relation, primaryKey);
return data;
}, this);
}
},
/**
Extract embedded objects out of the payload for a single object
and add them as sideloaded objects instead.
@method extractSingle
*/
extractSingle: function(store, primaryType, payload, recordId, requestType) {
var root = this.keyForAttribute(primaryType.typeKey),
partial = payload[root];
updatePayloadWithEmbedded(store, this, primaryType, partial, payload);
return this._super(store, primaryType, payload, recordId, requestType);
},
/**
Extract embedded objects out of a standard payload
and add them as sideloaded objects instead.
@method extractArray
*/
extractArray: function(store, type, payload) {
var root = this.keyForAttribute(type.typeKey),
partials = payload[pluralize(root)];
forEach(partials, function(partial) {
updatePayloadWithEmbedded(store, this, type, partial, payload);
}, this);
return this._super(store, type, payload);
}
});
function updatePayloadWithEmbedded(store, serializer, type, partial, payload) {
var attrs = get(serializer, 'attrs');
if (!attrs) {
return;
}
type.eachRelationship(function(key, relationship) {
var expandedKey, embeddedTypeKey, attribute, ids,
config = attrs[key],
serializer = store.serializerFor(relationship.type.typeKey),
primaryKey = get(serializer, "primaryKey");
if (relationship.kind !== "hasMany") {
return;
}
if (config && (config.embedded === 'always' || config.embedded === 'load')) {
// underscore forces the embedded records to be side loaded.
// it is needed when main type === relationship.type
embeddedTypeKey = '_' + Ember.String.pluralize(relationship.type.typeKey);
expandedKey = this.keyForRelationship(key, relationship.kind);
attribute = this.keyForAttribute(key);
ids = [];
if (!partial[attribute]) {
return;
}
payload[embeddedTypeKey] = payload[embeddedTypeKey] || [];
forEach(partial[attribute], function(data) {
var embeddedType = store.modelFor(relationship.type.typeKey);
updatePayloadWithEmbedded(store, serializer, embeddedType, data, payload);
ids.push(data[primaryKey]);
payload[embeddedTypeKey].push(data);
});
partial[expandedKey] = ids;
delete partial[attribute];
}
}, serializer);
}
__exports__["default"] = EmbeddedRecordsMixin;
});
define("ember-data/lib/adapters",
["./adapters/fixture_adapter","./adapters/rest_adapter","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var FixtureAdapter = __dependency1__["default"];
var RESTAdapter = __dependency2__["default"];
__exports__.RESTAdapter = RESTAdapter;
__exports__.FixtureAdapter = FixtureAdapter;
});
define("ember-data/lib/adapters/fixture_adapter",
["../system/adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get, fmt = Ember.String.fmt,
indexOf = Ember.EnumerableUtils.indexOf;
var counter = 0;
var Adapter = __dependency1__["default"];
/**
`DS.FixtureAdapter` is an adapter that loads records from memory.
Its primarily used for development and testing. You can also use
`DS.FixtureAdapter` while working on the API but are not ready to
integrate yet. It is a fully functioning adapter. All CRUD methods
are implemented. You can also implement query logic that a remote
system would do. Its possible to do develop your entire application
with `DS.FixtureAdapter`.
For information on how to use the `FixtureAdapter` in your
application please see the [FixtureAdapter
guide](/guides/models/the-fixture-adapter/).
@class FixtureAdapter
@namespace DS
@extends DS.Adapter
*/
var FixtureAdapter = Adapter.extend({
// by default, fixtures are already in normalized form
serializer: null,
/**
If `simulateRemoteResponse` is `true` the `FixtureAdapter` will
wait a number of milliseconds before resolving promises with the
fixture values. The wait time can be configured via the `latency`
property.
@property simulateRemoteResponse
@type {Boolean}
@default true
*/
simulateRemoteResponse: true,
/**
By default the `FixtureAdapter` will simulate a wait of the
`latency` milliseconds before resolving promises with the fixture
values. This behavior can be turned off via the
`simulateRemoteResponse` property.
@property latency
@type {Number}
@default 50
*/
latency: 50,
/**
Implement this method in order to provide data associated with a type
@method fixturesForType
@param {Subclass of DS.Model} type
@return {Array}
*/
fixturesForType: function(type) {
if (type.FIXTURES) {
var fixtures = Ember.A(type.FIXTURES);
return fixtures.map(function(fixture){
var fixtureIdType = typeof fixture.id;
if(fixtureIdType !== "number" && fixtureIdType !== "string"){
throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture]));
}
fixture.id = fixture.id + '';
return fixture;
});
}
return null;
},
/**
Implement this method in order to query fixtures data
@method queryFixtures
@param {Array} fixture
@param {Object} query
@param {Subclass of DS.Model} type
@return {Promise|Array}
*/
queryFixtures: function(fixtures, query, type) {
Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.');
},
/**
@method updateFixtures
@param {Subclass of DS.Model} type
@param {Array} fixture
*/
updateFixtures: function(type, fixture) {
if(!type.FIXTURES) {
type.FIXTURES = [];
}
var fixtures = type.FIXTURES;
this.deleteLoadedFixture(type, fixture);
fixtures.push(fixture);
},
/**
Implement this method in order to provide json for CRUD methods
@method mockJSON
@param {Subclass of DS.Model} type
@param {DS.Model} record
*/
mockJSON: function(store, type, record) {
return store.serializerFor(type).serialize(record, { includeId: true });
},
/**
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} record
@return {String} id
*/
generateIdForRecord: function(store) {
return "fixture-" + counter++;
},
/**
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@return {Promise} promise
*/
find: function(store, type, id) {
var fixtures = this.fixturesForType(type),
fixture;
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
if (fixtures) {
fixture = Ember.A(fixtures).findProperty('id', id);
}
if (fixture) {
return this.simulateRemoteCall(function() {
return fixture;
}, this);
}
},
/**
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array} ids
@return {Promise} promise
*/
findMany: function(store, type, ids) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
if (fixtures) {
fixtures = fixtures.filter(function(item) {
return indexOf(ids, item.id) !== -1;
});
}
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: function(store, type) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
},
/**
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: function(store, type, query, array) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type " + type.toString(), fixtures);
fixtures = this.queryFixtures(fixtures, query, type);
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.deleteLoadedFixture(type, fixture);
return this.simulateRemoteCall(function() {
// no payload in a deletion
return null;
});
},
/*
@method deleteLoadedFixture
@private
@param type
@param record
*/
deleteLoadedFixture: function(type, record) {
var existingFixture = this.findExistingFixture(type, record);
if(existingFixture) {
var index = indexOf(type.FIXTURES, existingFixture);
type.FIXTURES.splice(index, 1);
return true;
}
},
/*
@method findExistingFixture
@private
@param type
@param record
*/
findExistingFixture: function(type, record) {
var fixtures = this.fixturesForType(type);
var id = get(record, 'id');
return this.findFixtureById(fixtures, id);
},
/*
@method findFixtureById
@private
@param fixtures
@param id
*/
findFixtureById: function(fixtures, id) {
return Ember.A(fixtures).find(function(r) {
if(''+get(r, 'id') === ''+id) {
return true;
} else {
return false;
}
});
},
/*
@method simulateRemoteCall
@private
@param callback
@param context
*/
simulateRemoteCall: function(callback, context) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve) {
if (get(adapter, 'simulateRemoteResponse')) {
// Schedule with setTimeout
Ember.run.later(function() {
resolve(callback.call(context));
}, get(adapter, 'latency'));
} else {
// Asynchronous, but at the of the runloop with zero latency
Ember.run.schedule('actions', null, function() {
resolve(callback.call(context));
});
}
}, "DS: FixtureAdapter#simulateRemoteCall");
}
});
__exports__["default"] = FixtureAdapter;
});
define("ember-data/lib/adapters/rest_adapter",
["../system/adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Adapter = __dependency1__["default"];
var get = Ember.get, set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;
/**
The REST adapter allows your store to communicate with an HTTP server by
transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
should use the REST adapter.
This adapter is designed around the idea that the JSON exchanged with
the server should be conventional.
## JSON Structure
The REST adapter expects the JSON returned from your server to follow
these conventions.
### Object Root
The JSON payload should be an object that contains the record inside a
root property. For example, in response to a `GET` request for
`/posts/1`, the JSON should look like this:
```js
{
"post": {
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
}
}
```
### Conventional Names
Attribute names in your JSON payload should be the camelCased versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"person": {
"firstName": "Barack",
"lastName": "Obama",
"occupation": "President"
}
}
```
## Customization
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```js
DS.RESTAdapter.reopen({
namespace: 'api/1'
});
```
Requests for `App.Person` would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```js
DS.RESTAdapter.reopen({
host: 'https://api.example.com'
});
```
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. An array of
headers can be added to the adapter which are passed with every request:
```js
DS.RESTAdapter.reopen({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@class RESTAdapter
@constructor
@namespace DS
@extends DS.Adapter
*/
var RESTAdapter = Adapter.extend({
defaultSerializer: '-rest',
/**
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```javascript
DS.RESTAdapter.reopen({
namespace: 'api/1'
});
```
Requests for `App.Post` would now target `/api/1/post/`.
@property namespace
@type {String}
*/
/**
An adapter can target other hosts by setting the `host` property.
```javascript
DS.RESTAdapter.reopen({
host: 'https://api.example.com'
});
```
Requests for `App.Post` would now target `https://api.example.com/post/`.
@property host
@type {String}
*/
/**
Some APIs require HTTP headers, e.g. to provide an API key. An array of
headers can be added to the adapter which are passed with every request:
```javascript
DS.RESTAdapter.reopen({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@property headers
@type {Object}
*/
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
This method performs an HTTP `GET` request with the id provided as part of the query string.
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@returns {Promise} promise
*/
find: function(store, type, id) {
return this.ajax(this.buildURL(type.typeKey, id), 'GET');
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@returns {Promise} promise
*/
findAll: function(store, type, sinceToken) {
var query;
if (sinceToken) {
query = { since: sinceToken };
}
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@returns {Promise} promise
*/
findQuery: function(store, type, query) {
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as IDs.
For example, if the original payload looks like:
```js
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
```
The IDs will be passed as a URL-encoded Array of IDs, in this form:
```
ids[]=1&ids[]=2&ids[]=3
```
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array
into an Array for you on the server-side. If you want to encode the
IDs, differently, just override this (one-line) method.
The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array} ids
@returns {Promise} promise
*/
findMany: function(store, type, ids) {
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
```
This method will be called with the parent record and `/posts/1/comments`.
The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL.
If the URL is host-relative (starting with a single slash), the
request will use the host specified on the adapter (if any).
@method findHasMany
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@returns {Promise} promise
*/
findHasMany: function(store, record, url) {
var host = get(this, 'host'),
id = get(record, 'id'),
type = record.constructor.typeKey;
if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
url = host + url;
}
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a belongs-to relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
```
This method will be called with the parent record and `/people/1/group`.
The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findBelongsTo
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@returns {Promise} promise
*/
findBelongsTo: function(store, record, url) {
var id = get(record, 'id'),
type = record.constructor.typeKey;
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns {Promise} promise
*/
createRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record, { includeId: true });
return this.ajax(this.buildURL(type.typeKey), "POST", { data: data });
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns {Promise} promise
*/
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var id = get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data });
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns {Promise} promise
*/
deleteRecord: function(store, type, record) {
var id = get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id), "DELETE");
},
/**
Builds a URL for a given type and optional ID.
By default, it pluralizes the type's name (for example, 'post'
becomes 'posts' and 'person' becomes 'people'). To override the
pluralization see [pathForType](#method_pathForType).
If an ID is specified, it adds the ID to the path generated
for the type, separated by a `/`.
@method buildURL
@param {String} type
@param {String} id
@returns {String} url
*/
buildURL: function(type, id) {
var url = [],
host = get(this, 'host'),
prefix = this.urlPrefix();
if (type) { url.push(this.pathForType(type)); }
if (id) { url.push(id); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url) { url = '/' + url; }
return url;
},
/**
@method urlPrefix
@private
@param {String} path
@param {String} parentUrl
@return {String} urlPrefix
*/
urlPrefix: function(path, parentURL) {
var host = get(this, 'host'),
namespace = get(this, 'namespace'),
url = [];
if (path) {
// Absolute path
if (path.charAt(0) === '/') {
if (host) {
path = path.slice(1);
url.push(host);
}
// Relative path
} else if (!/^http(s)?:\/\//.test(path)) {
url.push(parentURL);
}
} else {
if (host) { url.push(host); }
if (namespace) { url.push(namespace); }
}
if (path) {
url.push(path);
}
return url.join('/');
},
/**
Determines the pathname for a given type.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
### Pathname customization
For example if you have an object LineItem with an
endpoint of "/line_items/".
```js
DS.RESTAdapter.reopen({
pathForType: function(type) {
var decamelized = Ember.String.decamelize(type);
return Ember.String.pluralize(decamelized);
};
});
```
@method pathForType
@param {String} type
@returns {String} path
**/
pathForType: function(type) {
var camelized = Ember.String.camelize(type);
return Ember.String.pluralize(camelized);
},
/**
Takes an ajax response, and returns a relevant error.
Returning a `DS.InvalidError` from this method will cause the
record to transition into the `invalid` state and make the
`errors` object available on the record.
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"];
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
Note: As a correctness optimization, the default implementation of
the `ajaxError` method strips out the `then` method from jquery's
ajax response (jqXHR). This is important because the jqXHR's
`then` method fulfills the promise with itself resulting in a
circular "thenable" chain which may cause problems for some
promise libraries.
@method ajaxError
@param {Object} jqXHR
@return {Object} jqXHR
*/
ajaxError: function(jqXHR) {
if (jqXHR) {
jqXHR.then = null;
}
return jqXHR;
},
/**
Takes a URL, an HTTP method and a hash of data, and makes an
HTTP request.
When the server responds with a payload, Ember Data will call into `extractSingle`
or `extractArray` (depending on whether the original query was for one record or
many records).
By default, `ajax` method has the following behavior:
* It sets the response `dataType` to `"json"`
* If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
`application/json; charset=utf-8`
* If the HTTP method is not `"GET"`, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
@method ajax
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} hash
@return {Promise} promise
*/
ajax: function(url, type, hash) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
hash = adapter.ajaxOptions(url, type, hash);
hash.success = function(json) {
Ember.run(null, resolve, json);
};
hash.error = function(jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, adapter.ajaxError(jqXHR));
};
Ember.$.ajax(hash);
}, "DS: RestAdapter#ajax " + type + " to " + url);
},
/**
@method ajaxOptions
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} hash
@return {Object} hash
*/
ajaxOptions: function(url, type, hash) {
hash = hash || {};
hash.url = url;
hash.type = type;
hash.dataType = 'json';
hash.context = this;
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
if (this.headers !== undefined) {
var headers = this.headers;
hash.beforeSend = function (xhr) {
forEach.call(Ember.keys(headers), function(key) {
xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
}
});
__exports__["default"] = RESTAdapter;
});
define("ember-data/lib/core",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
/**
All Ember Data methods and functions are defined inside of this namespace.
@class DS
@static
*/
var DS;
if ('undefined' === typeof DS) {
/**
@property VERSION
@type String
@default '1.0.0-beta.7+canary.b45e23ba'
@static
*/
DS = Ember.Namespace.create({
VERSION: '1.0.0-beta.7+canary.b45e23ba'
});
if ('undefined' !== typeof window) {
window.DS = DS;
}
if (Ember.libraries) {
Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION);
}
}
__exports__["default"] = DS;
});
define("ember-data/lib/ext/date",
[],
function() {
"use strict";
/**
@module ember-data
*/
/**
Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
© 2011 Colin Snover <http://zetafleet.com>
Released under MIT license.
@class Date
@namespace Ember
@static
*/
Ember.Date = Ember.Date || {};
var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
/**
@method parse
@param date
*/
Ember.Date.parse = function (date) {
var timestamp, struct, minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; (k = numericKeys[i]); ++i) {
struct[k] = +struct[k] || 0;
}
// allow undefined days and months
struct[2] = (+struct[2] || 1) - 1;
struct[3] = +struct[3] || 1;
if (struct[8] !== 'Z' && struct[9] !== undefined) {
minutesOffset = struct[10] * 60 + struct[11];
if (struct[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
}
timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
}
else {
timestamp = origParse ? origParse(date) : NaN;
}
return timestamp;
};
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) {
Date.parse = Ember.Date.parse;
}
});
define("ember-data/lib/initializers",
["./system/store","./serializers","./adapters","./system/debug/debug_adapter","./system/container_proxy","./transforms"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__) {
"use strict";
var Store = __dependency1__["default"];
var JSONSerializer = __dependency2__.JSONSerializer;
var RESTSerializer = __dependency2__.RESTSerializer;
var RESTAdapter = __dependency3__.RESTAdapter;
var DebugAdapter = __dependency4__["default"];
var ContainerProxy = __dependency5__["default"];
var BooleanTransform = __dependency6__.BooleanTransform;
var DateTransform = __dependency6__.DateTransform;
var StringTransform = __dependency6__.StringTransform;
var NumberTransform = __dependency6__.NumberTransform;
/**
@module ember-data
*/
var set = Ember.set;
/*
This code registers an injection for Ember.Application.
If an Ember.js developer defines a subclass of DS.Store on their application,
this code will automatically instantiate it and make it available on the
router.
Additionally, after an application's controllers have been injected, they will
each have the store made available to them.
For example, imagine an Ember.js application with the following classes:
App.Store = DS.Store.extend({
adapter: 'custom'
});
App.PostsController = Ember.ArrayController.extend({
// ...
});
When the application is initialized, `App.Store` will automatically be
instantiated, and the instance of `App.PostsController` will have its `store`
property set to that instance.
Note that this code will only be run if the `ember-application` package is
loaded. If Ember Data is being used in an environment other than a
typical application (e.g., node.js where only `ember-runtime` is available),
this code will be ignored.
*/
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "store",
initialize: function(container, application) {
application.register('store:main', application.Store || Store);
// allow older names to be looked up
var proxy = new ContainerProxy(container);
proxy.registerDeprecations([
{deprecated: 'serializer:_default', valid: 'serializer:-default'},
{deprecated: 'serializer:_rest', valid: 'serializer:-rest'},
{deprecated: 'adapter:_rest', valid: 'adapter:-rest'}
]);
// new go forward paths
application.register('serializer:-default', JSONSerializer);
application.register('serializer:-rest', RESTSerializer);
application.register('adapter:-rest', RESTAdapter);
// Eagerly generate the store so defaultStore is populated.
// TODO: Do this in a finisher hook
container.lookup('store:main');
}
});
Application.initializer({
name: "transforms",
before: "store",
initialize: function(container, application) {
application.register('transform:boolean', BooleanTransform);
application.register('transform:date', DateTransform);
application.register('transform:number', NumberTransform);
application.register('transform:string', StringTransform);
}
});
Application.initializer({
name: "data-adapter",
before: "store",
initialize: function(container, application) {
application.register('data-adapter:main', DebugAdapter);
}
});
Application.initializer({
name: "injectStore",
before: "store",
initialize: function(container, application) {
application.inject('controller', 'store', 'store:main');
application.inject('route', 'store', 'store:main');
application.inject('serializer', 'store', 'store:main');
application.inject('data-adapter', 'store', 'store:main');
}
});
});
});
define("ember-data/lib/main",
["./core","./ext/date","./system/store","./system/model","./system/changes","./system/adapter","./system/debug","./system/record_arrays","./system/record_array_manager","./adapters","./serializers/json_serializer","./serializers/rest_serializer","../../ember-inflector/lib/main","../../activemodel-adapter/lib/main","./transforms","./system/relationships","./initializers","./system/container_proxy","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __dependency16__, __dependency17__, __dependency18__, __exports__) {
"use strict";
/**
Ember Data
@module ember-data
@main ember-data
*/
// support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast
Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve;
var DS = __dependency1__["default"];
var Store = __dependency3__.Store;
var PromiseArray = __dependency3__.PromiseArray;
var PromiseObject = __dependency3__.PromiseObject;
var Model = __dependency4__.Model;
var Errors = __dependency4__.Errors;
var RootState = __dependency4__.RootState;
var attr = __dependency4__.attr;
var AttributeChange = __dependency5__.AttributeChange;
var RelationshipChange = __dependency5__.RelationshipChange;
var RelationshipChangeAdd = __dependency5__.RelationshipChangeAdd;
var RelationshipChangeRemove = __dependency5__.RelationshipChangeRemove;
var OneToManyChange = __dependency5__.OneToManyChange;
var ManyToNoneChange = __dependency5__.ManyToNoneChange;
var OneToOneChange = __dependency5__.OneToOneChange;
var ManyToManyChange = __dependency5__.ManyToManyChange;
var InvalidError = __dependency6__.InvalidError;
var Adapter = __dependency6__.Adapter;
var DebugAdapter = __dependency7__["default"];
var RecordArray = __dependency8__.RecordArray;
var FilteredRecordArray = __dependency8__.FilteredRecordArray;
var AdapterPopulatedRecordArray = __dependency8__.AdapterPopulatedRecordArray;
var ManyArray = __dependency8__.ManyArray;
var RecordArrayManager = __dependency9__["default"];
var RESTAdapter = __dependency10__.RESTAdapter;
var FixtureAdapter = __dependency10__.FixtureAdapter;
var JSONSerializer = __dependency11__["default"];
var RESTSerializer = __dependency12__["default"];
var ActiveModelAdapter = __dependency14__.ActiveModelAdapter;
var ActiveModelSerializer = __dependency14__.ActiveModelSerializer;
var EmbeddedRecordsMixin = __dependency14__.EmbeddedRecordsMixin;
var Transform = __dependency15__.Transform;
var DateTransform = __dependency15__.DateTransform;
var NumberTransform = __dependency15__.NumberTransform;
var StringTransform = __dependency15__.StringTransform;
var BooleanTransform = __dependency15__.BooleanTransform;
var hasMany = __dependency16__.hasMany;
var belongsTo = __dependency16__.belongsTo;
var ContainerProxy = __dependency18__["default"];
DS.Store = Store;
DS.PromiseArray = PromiseArray;
DS.PromiseObject = PromiseObject;
DS.Model = Model;
DS.RootState = RootState;
DS.attr = attr;
DS.Errors = Errors;
DS.AttributeChange = AttributeChange;
DS.RelationshipChange = RelationshipChange;
DS.RelationshipChangeAdd = RelationshipChangeAdd;
DS.OneToManyChange = OneToManyChange;
DS.ManyToNoneChange = OneToManyChange;
DS.OneToOneChange = OneToOneChange;
DS.ManyToManyChange = ManyToManyChange;
DS.Adapter = Adapter;
DS.InvalidError = InvalidError;
DS.DebugAdapter = DebugAdapter;
DS.RecordArray = RecordArray;
DS.FilteredRecordArray = FilteredRecordArray;
DS.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray;
DS.ManyArray = ManyArray;
DS.RecordArrayManager = RecordArrayManager;
DS.RESTAdapter = RESTAdapter;
DS.FixtureAdapter = FixtureAdapter;
DS.RESTSerializer = RESTSerializer;
DS.JSONSerializer = JSONSerializer;
DS.Transform = Transform;
DS.DateTransform = DateTransform;
DS.StringTransform = StringTransform;
DS.NumberTransform = NumberTransform;
DS.BooleanTransform = BooleanTransform;
DS.ActiveModelAdapter = ActiveModelAdapter;
DS.ActiveModelSerializer = ActiveModelSerializer;
DS.EmbeddedRecordsMixin = EmbeddedRecordsMixin;
DS.belongsTo = belongsTo;
DS.hasMany = hasMany;
DS.ContainerProxy = ContainerProxy;
__exports__["default"] = DS;
});
define("ember-data/lib/serializers",
["./serializers/json_serializer","./serializers/rest_serializer","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var JSONSerializer = __dependency1__["default"];
var RESTSerializer = __dependency2__["default"];
__exports__.JSONSerializer = JSONSerializer;
__exports__.RESTSerializer = RESTSerializer;
});
define("ember-data/lib/serializers/json_serializer",
["exports"],
function(__exports__) {
"use strict";
var get = Ember.get, set = Ember.set, isNone = Ember.isNone;
/**
In Ember Data a Serializer is used to serialize and deserialize
records when they are transferred in and out of an external source.
This process involves normalizing property names, transforming
attribute values and serializing relationships.
For maximum performance Ember Data recommends you use the
[RESTSerializer](DS.RESTSerializer.html) or one of its subclasses.
`JSONSerializer` is useful for simpler or legacy backends that may
not support the http://jsonapi.org/ spec.
@class JSONSerializer
@namespace DS
*/
var JSONSerializer = Ember.Object.extend({
/**
The primaryKey is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
primaryKey property to match the primaryKey of your external
store.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
@default 'id'
*/
primaryKey: 'id',
/**
Given a subclass of `DS.Model` and a JSON object this method will
iterate through each attribute of the `DS.Model` and invoke the
`DS.Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {subclass of DS.Model} type
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms: function(type, data) {
type.eachTransformedAttribute(function(key, type) {
var transform = this.transformFor(type);
data[key] = transform.deserialize(data[key]);
}, this);
return data;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalize: function(type, hash) {
var fields = Ember.get(type, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@return {Object}
*/
normalize: function(type, hash) {
if (!hash) { return hash; }
this.applyTransforms(type, hash);
return hash;
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```javascript
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapProperty('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```javascript
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = this._super.apply(this, arguments);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {subclass of DS.Model} record
@param {Object} options
@return {Object} json
*/
serialize: function(record, options) {
var json = {};
if (options && options.includeId) {
var id = get(record, 'id');
if (id) {
json[get(this, 'primaryKey')] = id;
}
}
record.eachAttribute(function(key, attribute) {
this.serializeAttribute(record, json, key, attribute);
}, this);
record.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(record, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(record, json, relationship);
}
}, this);
return json;
},
/**
`serializeAttribute` can be used to customize how `DS.attr`
properties are serialized
For example if you wanted to ensure all you attributes were always
serialized as properties on an `attributes` object you could
write:
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serializeAttribute: function(record, json, key, attributes) {
json.attributes = json.attributes || {};
this._super(record, json.attributes, key, attributes);
}
});
```
@method serializeAttribute
@param {DS.Model} record
@param {Object} json
@param {String} key
@param {Object} attribute
*/
serializeAttribute: function(record, json, key, attribute) {
var attrs = get(this, 'attrs');
var value = get(record, key), type = attribute.type;
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key);
json[key] = value;
},
/**
`serializeBelongsTo` can be used to customize how `DS.belongsTo`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON();
}
});
```
@method serializeBelongsTo
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
if (isNone(belongsTo)) {
json[key] = belongsTo;
} else {
json[key] = get(belongsTo, 'id');
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(record, json, relationship);
}
},
/**
`serializeHasMany` can be used to customize how `DS.hasMany`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
if (key === 'comments') {
return;
} else {
this._super.apply(this, arguments);
}
}
});
```
@method serializeHasMany
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') {
json[key] = get(record, key).mapBy('id');
// TODO support for polymorphic manyToNone and manyToMany relationships
}
},
/**
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
`{polymorphic: true}` is pass as the second argument to the
`DS.belongsTo` function.
Example
```javascript
App.CommentSerializer = DS.JSONSerializer.extend({
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
json[key + "_type"] = belongsTo.constructor.typeKey;
}
});
```
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: Ember.K,
// EXTRACT
/**
The `extract` method is used to deserialize payload data from the
server. By default the `JSONSerializer` does not push the records
into the store. However records that subclass `JSONSerializer`
such as the `RESTSerializer` may push records into the store as
part of the extract call.
This method delegates to a more specific extract method based on
the `requestType`.
Example
```javascript
var get = Ember.get;
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
var type = store.modelFor(modelName);
var serializer = store.serializerFor(type.typeKey);
var record = serializer.extract(store, type, data, get(data, 'id'), 'single');
store.push(modelName, record);
});
```
@method extract
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extract: function(store, type, payload, id, requestType) {
this.extractMeta(store, type, payload);
var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1);
return this[specificExtract](store, type, payload, id, requestType);
},
/**
`extractFindAll` is a hook into the extract method used when a
call is made to `DS.Store#findAll`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindAll: function(store, type, payload){
return this.extractArray(store, type, payload);
},
/**
`extractFindQuery` is a hook into the extract method used when a
call is made to `DS.Store#findQuery`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindQuery: function(store, type, payload){
return this.extractArray(store, type, payload);
},
/**
`extractFindMany` is a hook into the extract method used when a
call is made to `DS.Store#findMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindMany: function(store, type, payload){
return this.extractArray(store, type, payload);
},
/**
`extractFindHasMany` is a hook into the extract method used when a
call is made to `DS.Store#findHasMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindHasMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindHasMany: function(store, type, payload){
return this.extractArray(store, type, payload);
},
/**
`extractCreateRecord` is a hook into the extract method used when a
call is made to `DS.Store#createRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractCreateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractCreateRecord: function(store, type, payload) {
return this.extractSave(store, type, payload);
},
/**
`extractUpdateRecord` is a hook into the extract method used when
a call is made to `DS.Store#update`. By default this method is alias
for [extractSave](#method_extractSave).
@method extractUpdateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractUpdateRecord: function(store, type, payload) {
return this.extractSave(store, type, payload);
},
/**
`extractDeleteRecord` is a hook into the extract method used when
a call is made to `DS.Store#deleteRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractDeleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractDeleteRecord: function(store, type, payload) {
return this.extractSave(store, type, payload);
},
/**
`extractFind` is a hook into the extract method used when
a call is made to `DS.Store#find`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFind
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractFind: function(store, type, payload) {
return this.extractSingle(store, type, payload);
},
/**
`extractFindBelongsTo` is a hook into the extract method used when
a call is made to `DS.Store#findBelongsTo`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFindBelongsTo
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractFindBelongsTo: function(store, type, payload) {
return this.extractSingle(store, type, payload);
},
/**
`extractSave` is a hook into the extract method used when a call
is made to `DS.Model#save`. By default this method is alias
for [extractSingle](#method_extractSingle).
@method extractSave
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractSave: function(store, type, payload) {
return this.extractSingle(store, type, payload);
},
/**
`extractSingle` is used to deserialize a single record returned
from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractSingle: function(store, type, payload) {
payload.comments = payload._embedded.comment;
delete payload._embedded;
return this._super(store, type, payload);
},
});
```
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractSingle: function(store, type, payload) {
return this.normalize(type, payload);
},
/**
`extractArray` is used to deserialize an array of records
returned from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractArray: function(store, type, payload) {
return payload.map(function(json) {
return this.extractSingle(store, type, json);
}, this);
}
});
```
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractArray: function(store, type, payload) {
return this.normalize(type, payload);
},
/**
`extractMeta` is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the `meta` property of the payload object.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractMeta: function(store, type, payload) {
if (payload && payload._pagination) {
store.metaForType(type, payload._pagination);
delete payload._pagination;
}
}
});
```
@method extractMeta
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
*/
extractMeta: function(store, type, payload) {
if (payload && payload.meta) {
store.metaForType(type, payload.meta);
delete payload.meta;
}
},
/**
`keyForAttribute` can be used to define rules for how to convert an
attribute name in your model to a key in your JSON.
Example
```javascript
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
@method keyForAttribute
@param {String} key
@return {String} normalized key
*/
/**
`keyForRelationship` can be used to define a custom key when
serializing relationship properties. By default `JSONSerializer`
does not provide an implementation of this method.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
keyForRelationship: function(key, relationship) {
return 'rel_' + Ember.String.underscore(key);
}
});
```
@method keyForRelationship
@param {String} key
@param {String} relationship type
@return {String} normalized key
*/
// HELPERS
/**
@method transformFor
@private
@param {String} attributeType
@param {Boolean} skipAssertion
@return {DS.Transform} transform
*/
transformFor: function(attributeType, skipAssertion) {
var transform = this.container.lookup('transform:' + attributeType);
Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform);
return transform;
}
});
__exports__["default"] = JSONSerializer;
});
define("ember-data/lib/serializers/rest_serializer",
["./json_serializer","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var JSONSerializer = __dependency1__["default"];
var get = Ember.get, set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;
var map = Ember.ArrayPolyfills.map;
function coerceId(id) {
return id == null ? null : id+'';
}
/**
Normally, applications will use the `RESTSerializer` by implementing
the `normalize` method and individual normalizations under
`normalizeHash`.
This allows you to do whatever kind of munging you need, and is
especially useful if your server is inconsistent and you need to
do munging differently for many different kinds of responses.
See the `normalize` documentation for more information.
## Across the Board Normalization
There are also a number of hooks that you might find useful to defined
across-the-board rules for your payload. These rules will be useful
if your server is consistent, or if you're building an adapter for
an infrastructure service, like Parse, and want to encode service
conventions.
For example, if all of your keys are underscored and all-caps, but
otherwise consistent with the names you use in your models, you
can implement across-the-board rules for how to convert an attribute
name in your model to a key in your JSON.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
You can also implement `keyForRelationship`, which takes the name
of the relationship as the first parameter, and the kind of
relationship (`hasMany` or `belongsTo`) as the second parameter.
@class RESTSerializer
@namespace DS
@extends DS.JSONSerializer
*/
var RESTSerializer = JSONSerializer.extend({
/**
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, given the following json where the the `IDs` under
`"comments"` are provided as `_id` instead of `id`.
```javascript
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"_id": 1,
"body": "FIRST"
}, {
"_id": 2,
"body": "Rails is unagi"
}]
}
```
You use `normalizeHash` to normalize just the comments:
```javascript
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is usually just the original key
that was in the original payload. However, key names will be
impacted by any modifications done in the `normalizePayload`
method. The `DS.RESTSerializer`'s default implementation makes no
changes to the payload keys.
@property normalizeHash
@type {Object}
@default undefined
*/
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
For example, if you have a payload that looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"id": 1,
"body": "FIRST"
}, {
"id": 2,
"body": "Rails is unagi"
}]
}
```
The `normalize` method will be called three times:
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
`id`, you can specify how to normalize just the comments:
```js
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is just the original key that was in the original
payload.
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@returns {Object}
*/
normalize: function(type, hash, prop) {
this.normalizeId(hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
this.normalizeUsingDeclaredMapping(type, hash);
if (this.normalizeHash && this.normalizeHash[prop]) {
this.normalizeHash[prop](hash);
}
return this._super(type, hash, prop);
},
/**
You can use this method to normalize all payloads, regardless of whether they
represent single records or an array.
For example, you might want to remove some extraneous data from the payload:
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
normalizePayload: function(type, payload) {
delete payload.version;
delete payload.status;
return payload;
}
});
```
@method normalizePayload
@param {subclass of DS.Model} type
@param {Object} hash
@returns {Object} the normalized payload
*/
normalizePayload: function(type, payload) {
return payload;
},
/**
@method normalizeId
@private
*/
normalizeId: function(hash) {
var primaryKey = get(this, 'primaryKey');
if (primaryKey === 'id') { return; }
hash.id = hash[primaryKey];
delete hash[primaryKey];
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping: function(type, hash) {
var attrs = get(this, 'attrs'), payloadKey, key;
if (attrs) {
for (key in attrs) {
payloadKey = attrs[key];
if (payloadKey && payloadKey.key) {
payloadKey = payloadKey.key;
}
if (typeof payloadKey === 'string') {
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
/**
@method normalizeAttributes
@private
*/
normalizeAttributes: function(type, hash) {
var payloadKey, key;
if (this.keyForAttribute) {
type.eachAttribute(function(key) {
payloadKey = this.keyForAttribute(key);
if (key === payloadKey) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey, key;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
payloadKey = this.keyForRelationship(key, relationship.kind);
if (key === payloadKey) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
Called when the server has returned a payload representing
a single record, such as in response to a `find` or `save`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
post 1:
```js
{
"id": 1,
"title": "Rails is omakase",
"_embedded": {
"comment": [{
"_id": 1,
"comment_title": "FIRST"
}, {
"_id": 2,
"comment_title": "Rails is unagi"
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
extractSingle: function(store, type, payload, id, requestType) {
var comments = payload._embedded.comment;
delete payload._embedded;
payload = { comments: comments, post: payload };
return this._super(store, type, payload, id, requestType);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractSingle`, the
built-in implementation will find the primary record in your normalized
payload and push the remaining records into the store.
The primary record is the single hash found under `post` or the first
element of the `posts` array.
The primary record has special meaning when the record is being created
for the first time or updated (`createRecord` or `updateRecord`). In
particular, it will update the properties of the record that was saved.
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String} id
@param {'find'|'createRecord'|'updateRecord'|'deleteRecord'} requestType
@returns {Object} the primary response to the original request
*/
extractSingle: function(store, primaryType, payload, recordId, requestType) {
payload = this.normalizePayload(primaryType, payload);
var primaryTypeName = primaryType.typeKey,
primaryRecord;
for (var prop in payload) {
var typeName = this.typeForRoot(prop),
type = store.modelFor(typeName),
isPrimary = type.typeKey === primaryTypeName;
// legacy support for singular resources
if (isPrimary && Ember.typeOf(payload[prop]) !== "array" ) {
primaryRecord = this.normalize(primaryType, payload[prop], prop);
continue;
}
/*jshint loopfunc:true*/
forEach.call(payload[prop], function(hash) {
var typeName = this.typeForRoot(prop),
type = store.modelFor(typeName),
typeSerializer = store.serializerFor(type);
hash = typeSerializer.normalize(type, hash, prop);
var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord,
isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId;
// find the primary record.
//
// It's either:
// * the record with the same ID as the original request
// * in the case of a newly created record that didn't have an ID, the first
// record in the Array
if (isFirstCreatedRecord || isUpdatedRecord) {
primaryRecord = hash;
} else {
store.push(typeName, hash);
}
}, this);
}
return primaryRecord;
},
/**
Called when the server has returned a payload representing
multiple records, such as in response to a `findAll` or `findQuery`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
all posts:
```js
{
"_embedded": {
"post": [{
"id": 1,
"title": "Rails is omakase"
}, {
"id": 2,
"title": "The Parley Letter"
}],
"comment": [{
"_id": 1,
"comment_title": "Rails is unagi"
"post_id": 1
}, {
"_id": 2,
"comment_title": "Don't tread on me",
"post_id": 2
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
// and the comments are listed under a post's `comments` key.
extractArray: function(store, type, payload, id, requestType) {
var posts = payload._embedded.post;
var comments = [];
var postCache = {};
posts.forEach(function(post) {
post.comments = [];
postCache[post.id] = post;
});
payload._embedded.comment.forEach(function(comment) {
comments.push(comment);
postCache[comment.post_id].comments.push(comment);
delete comment.post_id;
}
payload = { comments: comments, posts: payload };
return this._super(store, type, payload, id, requestType);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractArray`, the
built-in implementation will find the primary array in your normalized
payload and push the remaining records into the store.
The primary array is the array found under `posts`.
The primary record has special meaning when responding to `findQuery`
or `findHasMany`. In particular, the primary array will become the
list of records in the record array that kicked off the request.
If your primary array contains secondary (embedded) records of the same type,
you cannot place these into the primary array `posts`. Instead, place the
secondary items into an underscore prefixed property `_posts`, which will
push these items into the store and will not affect the resulting query.
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {'findAll'|'findMany'|'findHasMany'|'findQuery'} requestType
@returns {Array} The primary array that was returned in response
to the original query.
*/
extractArray: function(store, primaryType, payload) {
payload = this.normalizePayload(primaryType, payload);
var primaryTypeName = primaryType.typeKey,
primaryArray;
for (var prop in payload) {
var typeKey = prop,
forcedSecondary = false;
if (prop.charAt(0) === '_') {
forcedSecondary = true;
typeKey = prop.substr(1);
}
var typeName = this.typeForRoot(typeKey),
type = store.modelFor(typeName),
typeSerializer = store.serializerFor(type),
isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName));
/*jshint loopfunc:true*/
var normalizedArray = map.call(payload[prop], function(hash) {
return typeSerializer.normalize(type, hash, prop);
}, this);
if (isPrimary) {
primaryArray = normalizedArray;
} else {
store.pushMany(typeName, normalizedArray);
}
}
return primaryArray;
},
/**
This method allows you to push a payload containing top-level
collections of records organized per type.
```js
{
"posts": [{
"id": "1",
"title": "Rails is omakase",
"author", "1",
"comments": [ "1" ]
}],
"comments": [{
"id": "1",
"body": "FIRST"
}],
"users": [{
"id": "1",
"name": "@d2h"
}]
}
```
It will first normalize the payload, so you can use this to push
in data streaming in from your server structured the same way
that fetches and saves are structured.
@method pushPayload
@param {DS.Store} store
@param {Object} payload
*/
pushPayload: function(store, payload) {
payload = this.normalizePayload(null, payload);
for (var prop in payload) {
var typeName = this.typeForRoot(prop),
type = store.modelFor(typeName);
/*jshint loopfunc:true*/
var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) {
return this.normalize(type, hash, prop);
}, this);
store.pushMany(typeName, normalizedArray);
}
},
/**
You can use this method to normalize the JSON root keys returned
into the model type expected by your store.
For example, your server may return underscored root keys rather than
the expected camelcased versions.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
typeForRoot: function(root) {
var camelized = Ember.String.camelize(root);
return Ember.String.singularize(camelized);
}
});
```
@method typeForRoot
@param {String} root
@returns {String} the model's typeKey
*/
typeForRoot: function(root) {
return Ember.String.singularize(root);
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```js
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```js
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapProperty('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```js
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = this._super(record, options);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param record
@param options
*/
serialize: function(record, options) {
return this._super.apply(this, arguments);
},
/**
You can use this method to customize the root keys serialized into the JSON.
By default the REST Serializer sends camelized root keys.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(hash, type, record, options) {
var root = Ember.String.camelize(type.typeKey);
hash[root] = this.serialize(record, options);
},
/**
You can use this method to customize how polymorphic objects are serialized.
By default the JSON Serializer creates the key by appending `Type` to
the attribute and value from the model's camelcased model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
json[key + "Type"] = Ember.String.camelize(belongsTo.constructor.typeKey);
}
});
__exports__["default"] = RESTSerializer;
});
define("ember-data/lib/system/adapter",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var map = Ember.ArrayPolyfills.map;
var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
/**
A `DS.InvalidError` is used by an adapter to signal the external API
was unable to process a request because the content was not
semantically correct or meaningful per the API. Usually this means a
record failed some form of server side validation. When a promise
from an adapter is rejected with a `DS.InvalidError` the record will
transition to the `invalid` state and the errors will be set to the
`errors` property on the record.
Example
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"];
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
The `DS.InvalidError` must be constructed with a single object whose
keys are the invalid model properties, and whose values are the
corresponding error messages. For example:
```javascript
return new DS.InvalidError({
length: 'Must be less than 15',
name: 'Must not be blank
});
```
@class InvalidError
@namespace DS
*/
var InvalidError = function(errors) {
var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors));
this.errors = errors;
for (var i=0, l=errorProps.length; i<l; i++) {
this[errorProps[i]] = tmp[errorProps[i]];
}
};
InvalidError.prototype = Ember.create(Error.prototype);
/**
An adapter is an object that receives requests from a store and
translates them into the appropriate action to take against your
persistence layer. The persistence layer is usually an HTTP API, but
may be anything, such as the browser's local storage. Typically the
adapter is not invoked directly instead its functionality is accessed
through the `store`.
### Creating an Adapter
First, create a new subclass of `DS.Adapter`:
```javascript
App.MyAdapter = DS.Adapter.extend({
// ...your code here
});
```
To tell your store which adapter to use, set its `adapter` property:
```javascript
App.store = DS.Store.create({
adapter: 'MyAdapter'
});
```
`DS.Adapter` is an abstract base class that you should override in your
application to customize it for your backend. The minimum set of methods
that you should implement is:
* `find()`
* `createRecord()`
* `updateRecord()`
* `deleteRecord()`
* `findAll()`
* `findQuery()`
To improve the network performance of your application, you can optimize
your adapter by overriding these lower-level methods:
* `findMany()`
For an example implementation, see `DS.RESTAdapter`, the
included REST adapter.
@class Adapter
@namespace DS
@extends Ember.Object
*/
var Adapter = Ember.Object.extend({
/**
If you would like your adapter to use a custom serializer you can
set the `defaultSerializer` property to be the name of the custom
serializer.
Note the `defaultSerializer` serializer has a lower priority then
a model specific serializer (i.e. `PostSerializer`) or the
`application` serializer.
```javascript
var DjangoAdapter = DS.Adapter.extend({
defaultSerializer: 'django'
});
```
@property defaultSerializer
@type {String}
*/
/**
The `find()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `find()` being called, you
should query your persistence layer for a record with the given ID. Once
found, you can asynchronously call the store's `push()` method to push
the record into the store.
Here is an example `find` implementation:
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
find: function(store, type, id) {
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@return {Promise} promise
*/
find: Ember.required(Function),
/**
The `findAll()` method is called when you call `find` on the store
without an ID (i.e. `store.find('post')`).
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findAll: function(store, type, sinceToken) {
var url = type;
var query = { since: sinceToken };
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: null,
/**
This method is called when you call `find` on the store with a
query object as the second parameter (i.e. `store.find('person', {
page: 1 })`).
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findQuery: function(store, type, query) {
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: null,
/**
If the globally unique IDs for your records should be generated on the client,
implement the `generateIdForRecord()` method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's `primaryKey`.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls `didCreateRecord()`. Only implement this method if
you intend to generate record IDs on the client-side.
The `generateIdForRecord()` method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
```javascript
generateIdForRecord: function(store, record) {
var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision();
return uuid;
}
```
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} record
@return {String|Number} id
*/
generateIdForRecord: null,
/**
Proxies to the serializer's `serialize` method.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
createRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var url = type;
// ...
}
});
```
@method serialize
@param {DS.Model} record
@param {Object} options
@return {Object} serialized record
*/
serialize: function(record, options) {
return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options);
},
/**
Implement this method in a subclass to handle the creation of
new records.
Serializes the record and send it to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
createRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the updating of
a record.
Serializes the record update and send it to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
updateRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var id = record.get('id');
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'PUT',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the deletion of
a record.
Sends a delete request for the record to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
deleteRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var id = record.get('id');
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'DELETE',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: Ember.required(Function),
/**
Find multiple records at once.
By default, it loops over the provided ids and calls `find` on each.
May be overwritten to improve performance and reduce the number of
server requests.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findMany: function(store, type, ids) {
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, {ids: ids}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the records
@param {Array} ids
@return {Promise} promise
*/
findMany: function(store, type, ids) {
var promises = map.call(ids, function(id) {
return this.find(store, type, id);
}, this);
return Ember.RSVP.all(promises);
}
});
__exports__.InvalidError = InvalidError;
__exports__.Adapter = Adapter;
__exports__["default"] = Adapter;
});
define("ember-data/lib/system/changes",
["./changes/attribute_change","./changes/relationship_change","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var AttributeChange = __dependency1__["default"];
var RelationshipChange = __dependency2__.RelationshipChange;
var RelationshipChangeAdd = __dependency2__.RelationshipChangeAdd;
var RelationshipChangeRemove = __dependency2__.RelationshipChangeRemove;
var OneToManyChange = __dependency2__.OneToManyChange;
var ManyToNoneChange = __dependency2__.ManyToNoneChange;
var OneToOneChange = __dependency2__.OneToOneChange;
var ManyToManyChange = __dependency2__.ManyToManyChange;
__exports__.AttributeChange = AttributeChange;
__exports__.RelationshipChange = RelationshipChange;
__exports__.RelationshipChangeAdd = RelationshipChangeAdd;
__exports__.RelationshipChangeRemove = RelationshipChangeRemove;
__exports__.OneToManyChange = OneToManyChange;
__exports__.ManyToNoneChange = ManyToNoneChange;
__exports__.OneToOneChange = OneToOneChange;
__exports__.ManyToManyChange = ManyToManyChange;
});
define("ember-data/lib/system/changes/attribute_change",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
/**
An AttributeChange object is created whenever a record's
attribute changes value. It is used to track changes to a
record between transaction commits.
@class AttributeChange
@namespace DS
@private
@constructor
*/
function AttributeChange(options) {
this.record = options.record;
this.store = options.store;
this.name = options.name;
this.value = options.value;
this.oldValue = options.oldValue;
}
AttributeChange.createChange = function(options) {
return new AttributeChange(options);
};
AttributeChange.prototype = {
sync: function() {
if (this.value !== this.oldValue) {
this.record.send('becomeDirty');
this.record.updateRecordArraysLater();
}
// TODO: Use this object in the commit process
this.destroy();
},
/**
If the AttributeChange is destroyed (either by being rolled back
or being committed), remove it from the list of pending changes
on the record.
@method destroy
*/
destroy: function() {
delete this.record._changesToSync[this.name];
}
};
__exports__["default"] = AttributeChange;
});
define("ember-data/lib/system/changes/relationship_change",
["../model","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__.Model;
var get = Ember.get, set = Ember.set;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RelationshipChange
@namespace DS
@private
@constructor
*/
var RelationshipChange = function(options) {
this.parentRecord = options.parentRecord;
this.childRecord = options.childRecord;
this.firstRecord = options.firstRecord;
this.firstRecordKind = options.firstRecordKind;
this.firstRecordName = options.firstRecordName;
this.secondRecord = options.secondRecord;
this.secondRecordKind = options.secondRecordKind;
this.secondRecordName = options.secondRecordName;
this.changeType = options.changeType;
this.store = options.store;
this.committed = {};
};
/**
@class RelationshipChangeAdd
@namespace DS
@private
@constructor
*/
var RelationshipChangeAdd = function(options){
RelationshipChange.call(this, options);
};
/**
@class RelationshipChangeRemove
@namespace DS
@private
@constructor
*/
var RelationshipChangeRemove = function(options){
RelationshipChange.call(this, options);
};
RelationshipChange.create = function(options) {
return new RelationshipChange(options);
};
RelationshipChangeAdd.create = function(options) {
return new RelationshipChangeAdd(options);
};
RelationshipChangeRemove.create = function(options) {
return new RelationshipChangeRemove(options);
};
var OneToManyChange = {};
var OneToNoneChange = {};
var ManyToNoneChange = {};
var OneToOneChange = {};
var ManyToManyChange = {};
RelationshipChange._createChange = function(options){
if(options.changeType === "add"){
return RelationshipChangeAdd.create(options);
}
if(options.changeType === "remove"){
return RelationshipChangeRemove.create(options);
}
};
RelationshipChange.determineRelationshipType = function(recordType, knownSide){
var knownKey = knownSide.key, key, otherKind;
var knownKind = knownSide.kind;
var inverse = recordType.inverseFor(knownKey);
if (inverse){
key = inverse.name;
otherKind = inverse.kind;
}
if (!inverse){
return knownKind === "belongsTo" ? "oneToNone" : "manyToNone";
}
else{
if(otherKind === "belongsTo"){
return knownKind === "belongsTo" ? "oneToOne" : "manyToOne";
}
else{
return knownKind === "belongsTo" ? "oneToMany" : "manyToMany";
}
}
};
RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){
// Get the type of the child based on the child's client ID
var firstRecordType = firstRecord.constructor, changeType;
changeType = RelationshipChange.determineRelationshipType(firstRecordType, options);
if (changeType === "oneToMany"){
return OneToManyChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToOne"){
return OneToManyChange.createChange(secondRecord, firstRecord, store, options);
}
else if (changeType === "oneToNone"){
return OneToNoneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToNone"){
return ManyToNoneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "oneToOne"){
return OneToOneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToMany"){
return ManyToManyChange.createChange(firstRecord, secondRecord, store, options);
}
};
OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) {
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
store: store,
changeType: options.changeType,
firstRecordName: key,
firstRecordKind: "belongsTo"
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) {
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: childRecord,
childRecord: parentRecord,
secondRecord: childRecord,
store: store,
changeType: options.changeType,
secondRecordName: options.key,
secondRecordKind: "hasMany"
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) {
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "hasMany",
secondRecordKind: "hasMany",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
OneToOneChange.createChange = function(childRecord, parentRecord, store, options) {
var key;
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
if (options.parentType) {
key = options.parentType.inverseFor(options.key).name;
} else if (options.key) {
key = options.key;
} else {
Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false);
}
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "belongsTo",
secondRecordKind: "belongsTo",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
OneToOneChange.maintainInvariant = function(options, store, childRecord, key){
if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) {
var oldParent = get(childRecord, key);
if (oldParent){
var correspondingChange = OneToOneChange.createChange(childRecord, oldParent, store, {
parentType: options.parentType,
hasManyName: options.hasManyName,
changeType: "remove",
key: options.key
});
store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange);
correspondingChange.sync();
}
}
};
OneToManyChange.createChange = function(childRecord, parentRecord, store, options) {
var key;
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
if (options.parentType) {
key = options.parentType.inverseFor(options.key).name;
OneToManyChange.maintainInvariant( options, store, childRecord, key );
} else if (options.key) {
key = options.key;
} else {
Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false);
}
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "belongsTo",
secondRecordKind: "hasMany",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change);
return change;
};
OneToManyChange.maintainInvariant = function(options, store, childRecord, key){
if (options.changeType === "add" && childRecord) {
var oldParent = get(childRecord, key);
if (oldParent){
var correspondingChange = OneToManyChange.createChange(childRecord, oldParent, store, {
parentType: options.parentType,
hasManyName: options.hasManyName,
changeType: "remove",
key: options.key
});
store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange);
correspondingChange.sync();
}
}
};
/**
@class RelationshipChange
@namespace DS
*/
RelationshipChange.prototype = {
getSecondRecordName: function() {
var name = this.secondRecordName, parent;
if (!name) {
parent = this.secondRecord;
if (!parent) { return; }
var childType = this.firstRecord.constructor;
var inverse = childType.inverseFor(this.firstRecordName);
this.secondRecordName = inverse.name;
}
return this.secondRecordName;
},
/**
Get the name of the relationship on the belongsTo side.
@method getFirstRecordName
@return {String}
*/
getFirstRecordName: function() {
var name = this.firstRecordName;
return name;
},
/**
@method destroy
@private
*/
destroy: function() {
var childRecord = this.childRecord,
belongsToName = this.getFirstRecordName(),
hasManyName = this.getSecondRecordName(),
store = this.store;
store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType);
},
getSecondRecord: function(){
return this.secondRecord;
},
/**
@method getFirstRecord
@private
*/
getFirstRecord: function() {
return this.firstRecord;
},
coalesce: function(){
var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord);
forEach(relationshipPairs, function(pair){
var addedChange = pair["add"];
var removedChange = pair["remove"];
if(addedChange && removedChange) {
addedChange.destroy();
removedChange.destroy();
}
});
}
};
RelationshipChangeAdd.prototype = Ember.create(RelationshipChange.create({}));
RelationshipChangeRemove.prototype = Ember.create(RelationshipChange.create({}));
// the object is a value, and not a promise
function isValue(object) {
return typeof object === 'object' && (!object.then || typeof object.then !== 'function');
}
RelationshipChangeAdd.prototype.changeType = "add";
RelationshipChangeAdd.prototype.sync = function() {
var secondRecordName = this.getSecondRecordName(),
firstRecordName = this.getFirstRecordName(),
firstRecord = this.getFirstRecord(),
secondRecord = this.getSecondRecord();
//Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName);
//Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName);
if (secondRecord instanceof Model && firstRecord instanceof Model) {
if(this.secondRecordKind === "belongsTo"){
secondRecord.suspendRelationshipObservers(function(){
set(secondRecord, secondRecordName, firstRecord);
});
}
else if(this.secondRecordKind === "hasMany"){
secondRecord.suspendRelationshipObservers(function(){
var relationship = get(secondRecord, secondRecordName);
if (isValue(relationship)) { relationship.addObject(firstRecord); }
});
}
}
if (firstRecord instanceof Model && secondRecord instanceof Model && get(firstRecord, firstRecordName) !== secondRecord) {
if(this.firstRecordKind === "belongsTo"){
firstRecord.suspendRelationshipObservers(function(){
set(firstRecord, firstRecordName, secondRecord);
});
}
else if(this.firstRecordKind === "hasMany"){
firstRecord.suspendRelationshipObservers(function(){
var relationship = get(firstRecord, firstRecordName);
if (isValue(relationship)) { relationship.addObject(secondRecord); }
});
}
}
this.coalesce();
};
RelationshipChangeRemove.prototype.changeType = "remove";
RelationshipChangeRemove.prototype.sync = function() {
var secondRecordName = this.getSecondRecordName(),
firstRecordName = this.getFirstRecordName(),
firstRecord = this.getFirstRecord(),
secondRecord = this.getSecondRecord();
//Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName);
//Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName);
if (secondRecord instanceof Model && firstRecord instanceof Model) {
if(this.secondRecordKind === "belongsTo"){
secondRecord.suspendRelationshipObservers(function(){
set(secondRecord, secondRecordName, null);
});
}
else if(this.secondRecordKind === "hasMany"){
secondRecord.suspendRelationshipObservers(function(){
var relationship = get(secondRecord, secondRecordName);
if (isValue(relationship)) { relationship.removeObject(firstRecord); }
});
}
}
if (firstRecord instanceof Model && get(firstRecord, firstRecordName)) {
if(this.firstRecordKind === "belongsTo"){
firstRecord.suspendRelationshipObservers(function(){
set(firstRecord, firstRecordName, null);
});
}
else if(this.firstRecordKind === "hasMany"){
firstRecord.suspendRelationshipObservers(function(){
var relationship = get(firstRecord, firstRecordName);
if (isValue(relationship)) { relationship.removeObject(secondRecord); }
});
}
}
this.coalesce();
};
__exports__.RelationshipChange = RelationshipChange;
__exports__.RelationshipChangeAdd = RelationshipChangeAdd;
__exports__.RelationshipChangeRemove = RelationshipChangeRemove;
__exports__.OneToManyChange = OneToManyChange;
__exports__.ManyToNoneChange = ManyToNoneChange;
__exports__.OneToOneChange = OneToOneChange;
__exports__.ManyToManyChange = ManyToManyChange;
});
define("ember-data/lib/system/container_proxy",
["exports"],
function(__exports__) {
"use strict";
/**
This is used internally to enable deprecation of container paths and provide
a decent message to the user indicating how to fix the issue.
@class ContainerProxy
@namespace DS
@private
*/
var ContainerProxy = function (container){
this.container = container;
};
ContainerProxy.prototype.aliasedFactory = function(path, preLookup) {
var _this = this;
return {create: function(){
if (preLookup) { preLookup(); }
return _this.container.lookup(path);
}};
};
ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) {
var factory = this.aliasedFactory(dest, preLookup);
return this.container.register(source, factory);
};
ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) {
var preLookupCallback = function(){
Ember.deprecate("You tried to look up '" + deprecated + "', " +
"but this has been deprecated in favor of '" + valid + "'.", false);
};
return this.registerAlias(deprecated, valid, preLookupCallback);
};
ContainerProxy.prototype.registerDeprecations = function(proxyPairs) {
for (var i = proxyPairs.length; i > 0; i--) {
var proxyPair = proxyPairs[i - 1],
deprecated = proxyPair['deprecated'],
valid = proxyPair['valid'];
this.registerDeprecation(deprecated, valid);
}
};
__exports__["default"] = ContainerProxy;
});
define("ember-data/lib/system/debug",
["./debug/debug_info","./debug/debug_adapter","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var DebugAdapter = __dependency2__["default"];
__exports__["default"] = DebugAdapter;
});
define("ember-data/lib/system/debug/debug_adapter",
["../model","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__.Model;
var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore;
/**
Extend `Ember.DataAdapter` with ED specific code.
@class DebugAdapter
@namespace DS
@extends Ember.DataAdapter
@private
*/
var DebugAdapter = Ember.DataAdapter.extend({
getFilters: function() {
return [
{ name: 'isNew', desc: 'New' },
{ name: 'isModified', desc: 'Modified' },
{ name: 'isClean', desc: 'Clean' }
];
},
detect: function(klass) {
return klass !== Model && Model.detect(klass);
},
columnsForType: function(type) {
var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this;
get(type, 'attributes').forEach(function(name, meta) {
if (count++ > self.attributeLimit) { return false; }
var desc = capitalize(underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords: function(type) {
return this.get('store').all(type);
},
getRecordColumnValues: function(record) {
var self = this, count = 0,
columnValues = { id: get(record, 'id') };
record.eachAttribute(function(key) {
if (count++ > self.attributeLimit) {
return false;
}
var value = get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords: function(record) {
var keywords = [], keys = Ember.A(['id']);
record.eachAttribute(function(key) {
keys.push(key);
});
keys.forEach(function(key) {
keywords.push(get(record, key));
});
return keywords;
},
getRecordFilterValues: function(record) {
return {
isNew: record.get('isNew'),
isModified: record.get('isDirty') && !record.get('isNew'),
isClean: !record.get('isDirty')
};
},
getRecordColor: function(record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('isDirty')) {
color = 'blue';
}
return color;
},
observeRecord: function(record, recordUpdated) {
var releaseMethods = Ember.A(), self = this,
keysToObserve = Ember.A(['id', 'isNew', 'isDirty']);
record.eachAttribute(function(key) {
keysToObserve.push(key);
});
keysToObserve.forEach(function(key) {
var handler = function() {
recordUpdated(self.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function() {
Ember.removeObserver(record, key, handler);
});
});
var release = function() {
releaseMethods.forEach(function(fn) { fn(); } );
};
return release;
}
});
__exports__["default"] = DebugAdapter;
});
define("ember-data/lib/system/debug/debug_info",
["../model","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Model = __dependency1__.Model;
Model.reopen({
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo: function() {
var attributes = ['id'],
relationships = { belongsTo: [], hasMany: [] },
expensiveProperties = [];
this.eachAttribute(function(name, meta) {
attributes.push(name);
}, this);
this.eachRelationship(function(name, relationship) {
relationships[relationship.kind].push(name);
expensiveProperties.push(name);
});
var groups = [
{
name: 'Attributes',
properties: attributes,
expand: true
},
{
name: 'Belongs To',
properties: relationships.belongsTo,
expand: true
},
{
name: 'Has Many',
properties: relationships.hasMany,
expand: true
},
{
name: 'Flags',
properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
}
];
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
}
});
__exports__["default"] = Model;
});
define("ember-data/lib/system/model",
["./model/model","./model/attributes","./model/states","./model/errors","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__["default"];
var attr = __dependency2__["default"];
var RootState = __dependency3__["default"];
var Errors = __dependency4__["default"];
__exports__.Model = Model;
__exports__.RootState = RootState;
__exports__.attr = attr;
__exports__.Errors = Errors;
});
define("ember-data/lib/system/model/attributes",
["./model","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Model = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get;
/**
@class Model
@namespace DS
*/
Model.reopenClass({
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
var attributes = Ember.get(App.Person, 'attributes')
attributes.forEach(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isAttribute) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');
meta.name = name;
map.set(name, meta);
}
});
return map;
}),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
var transformedAttributes = Ember.get(App.Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function() {
var map = Ember.Map.create();
this.eachAttribute(function(key, meta) {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachAttribute: function(callback, binding) {
get(this, 'attributes').forEach(function(name, meta) {
callback.call(binding, name, meta);
}, binding);
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a string containing the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachTransformedAttribute: function(callback, binding) {
get(this, 'transformedAttributes').forEach(function(name, type) {
callback.call(binding, name, type);
});
}
});
Model.reopen({
eachAttribute: function(callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
function getDefaultValue(record, options, key) {
if (typeof options.defaultValue === "function") {
return options.defaultValue.apply(null, arguments);
} else {
return options.defaultValue;
}
}
function hasValue(record, key) {
return record._attributes.hasOwnProperty(key) ||
record._inFlightAttributes.hasOwnProperty(key) ||
record._data.hasOwnProperty(key);
}
function getValue(record, key) {
if (record._attributes.hasOwnProperty(key)) {
return record._attributes[key];
} else if (record._inFlightAttributes.hasOwnProperty(key)) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
/**
`DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html).
By default, attributes are passed through as-is, however you can specify an
optional type to have the value automatically transformed.
Ember Data ships with four basic transform types: `string`, `number`,
`boolean` and `date`. You can define your own transforms by subclassing
[DS.Transform](/api/data/classes/DS.Transform.html).
`DS.attr` takes an optional hash as a second parameter, currently
supported options are:
- `defaultValue`: Pass a string or a function to be called to set the attribute
to a default value if none is supplied.
Example
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
username: attr('string'),
email: attr('string'),
verified: attr('boolean', {defaultValue: false})
});
```
@namespace
@method attr
@for DS
@param {String} type the attribute type
@param {Object} options a hash of options
@return {Attribute}
*/
function attr(type, options) {
options = options || {};
var meta = {
type: type,
isAttribute: true,
options: options
};
return Ember.computed('data', function(key, value) {
if (arguments.length > 1) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id');
var oldValue = getValue(this, key);
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
this._attributes[key] = value;
this.send('didSetProperty', {
name: key,
oldValue: oldValue,
originalValue: this._data[key],
value: value
});
}
return value;
} else if (hasValue(this, key)) {
return getValue(this, key);
} else {
return getDefaultValue(this, options, key);
}
// `data` is never set directly. However, it may be
// invalidated from the state manager's setData
// event.
}).meta(meta);
}
__exports__["default"] = attr;
});
define("ember-data/lib/system/model/errors",
["exports"],
function(__exports__) {
"use strict";
var get = Ember.get, isEmpty = Ember.isEmpty;
/**
@module ember-data
*/
/**
Holds validation errors for a given record organized by attribute names.
@class Errors
@namespace DS
@extends Ember.Object
@uses Ember.Enumerable
@uses Ember.Evented
*/
var Errors = Ember.Object.extend(Ember.Enumerable, Ember.Evented, {
/**
Register with target handler
@method registerHandlers
@param {Object} target
@param {Function} becameInvalid
@param {Function} becameValid
*/
registerHandlers: function(target, becameInvalid, becameValid) {
this.on('becameInvalid', target, becameInvalid);
this.on('becameValid', target, becameValid);
},
/**
@property errorsByAttributeName
@type {Ember.MapWithDefault}
@private
*/
errorsByAttributeName: Ember.reduceComputed("content", {
initialValue: function() {
return Ember.MapWithDefault.create({
defaultValue: function() {
return Ember.A();
}
});
},
addedItem: function(errors, error) {
errors.get(error.attribute).pushObject(error);
return errors;
},
removedItem: function(errors, error) {
errors.get(error.attribute).removeObject(error);
return errors;
}
}),
/**
Returns errors for a given attribute
@method errorsFor
@param {String} attribute
@returns {Array}
*/
errorsFor: function(attribute) {
return get(this, 'errorsByAttributeName').get(attribute);
},
/**
*/
messages: Ember.computed.mapBy('content', 'message'),
/**
@property content
@type {Array}
@private
*/
content: Ember.computed(function() {
return Ember.A();
}),
/**
@method unknownProperty
@private
*/
unknownProperty: function(attribute) {
var errors = this.errorsFor(attribute);
if (isEmpty(errors)) { return null; }
return errors;
},
/**
@method nextObject
@private
*/
nextObject: function(index, previousObject, context) {
return get(this, 'content').objectAt(index);
},
/**
Total number of errors.
@property length
@type {Number}
@readOnly
*/
length: Ember.computed.oneWay('content.length').readOnly(),
/**
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: Ember.computed.not('length').readOnly(),
/**
Adds error messages to a given attribute and sends
`becameInvalid` event to the record.
@method add
@param {String} attribute
@param {Array|String} messages
*/
add: function(attribute, messages) {
var wasEmpty = get(this, 'isEmpty');
messages = this._findOrCreateMessages(attribute, messages);
get(this, 'content').addObjects(messages);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (wasEmpty && !get(this, 'isEmpty')) {
this.trigger('becameInvalid');
}
},
/**
@method _findOrCreateMessages
@private
*/
_findOrCreateMessages: function(attribute, messages) {
var errors = this.errorsFor(attribute);
return Ember.makeArray(messages).map(function(message) {
return errors.findBy('message', message) || {
attribute: attribute,
message: message
};
});
},
/**
Removes all error messages from the given attribute and sends
`becameValid` event to the record if there no more errors left.
@method remove
@param {String} attribute
*/
remove: function(attribute) {
if (get(this, 'isEmpty')) { return; }
var content = get(this, 'content').rejectBy('attribute', attribute);
get(this, 'content').setObjects(content);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (get(this, 'isEmpty')) {
this.trigger('becameValid');
}
},
/**
Removes all error messages and sends `becameValid` event
to the record.
@method clear
*/
clear: function() {
if (get(this, 'isEmpty')) { return; }
get(this, 'content').clear();
this.enumerableContentDidChange();
this.trigger('becameValid');
},
/**
Checks if there is error messages for the given attribute.
@method has
@param {String} attribute
@returns {Boolean} true if there some errors on given attribute
*/
has: function(attribute) {
return !isEmpty(this.errorsFor(attribute));
}
});
__exports__["default"] = Errors;
});
define("ember-data/lib/system/model/model",
["./states","./errors","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var RootState = __dependency1__["default"];
var Errors = __dependency2__["default"];
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set,
merge = Ember.merge,
Promise = Ember.RSVP.Promise;
var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) {
return get(get(this, 'currentState'), key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
var Model = Ember.Object.extend(Ember.Evented, {
_recordArrays: undefined,
_relationships: undefined,
_loadingRecordArrays: undefined,
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isDirty'); // true
store.find('model', 1).then(function(model) {
model.get('isDirty'); // false
model.set('foo', 'some value');
model.set('isDirty'); // true
});
```
@property isDirty
@type {Boolean}
@readOnly
*/
isDirty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`isDirty` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `isDirty` and `isSaving` are false, the
change has persisted.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isDeleted'); // false
record.deleteRecord();
record.get('isDeleted'); // true
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state. A
record will be in the `valid` state when no client-side
validations have failed and the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend. This may also result in the record having
its `isValid` property become false if the adapter reported that
server-side validations failed.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'invalid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record form the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
The `clientId` property is a transient numerical identifier
generated at runtime by the data store. It is important
primarily because newly created objects may not yet have an
externally generated id.
@property clientId
@private
@type {Number|String}
*/
clientId: null,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
var record = store.createRecord(App.Model);
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
currentState: RootState.empty,
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
typically contains keys corresponding to the invalid property names
and values which are an array of error messages.
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().then(null, function() {
record.get('errors').get('foo'); // ['foo should be a number.']
});
```
@property errors
@type {Object}
*/
errors: Ember.computed(function() {
var errors = Errors.create();
errors.registerHandlers(this, function() {
this.send('becameInvalid');
}, function() {
this.send('becameValid');
});
return errors;
}).readOnly(),
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@returns {Object} an object whose values are primitive JSON values only
*/
serialize: function(options) {
var store = get(this, 'store');
return store.serialize(this, options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@returns {Object} A JSON representation of the object.
*/
toJSON: function(options) {
// container is for lazy transform lookups
var serializer = DS.JSONSerializer.create({ container: this.container });
return serializer.serialize(this, options);
},
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: Ember.K,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: Ember.K,
/**
Fired when the record is created.
@event didCreate
*/
didCreate: Ember.K,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: Ember.K,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: Ember.K,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: Ember.K,
/**
@property data
@private
@type {Object}
*/
data: Ember.computed(function() {
this._data = this._data || {};
return this._data;
}).readOnly(),
_data: null,
init: function() {
this._super();
this._setup();
},
_setup: function() {
this._changesToSync = {};
this._deferredTriggers = [];
this._data = {};
this._attributes = {};
this._inFlightAttributes = {};
this._relationships = {};
},
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function(name, context) {
var currentState = get(this, 'currentState');
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function(name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct references to state objects
var pivotName = name.split(".", 1),
currentState = get(this, 'currentState'),
state = currentState;
do {
if (state.exit) { state.exit(this); }
state = state.parentState;
} while (!state.hasOwnProperty(pivotName));
var path = name.split(".");
var setups = [], enters = [], i, l;
for (i=0, l=path.length; i<l; i++) {
state = state[path[i]];
if (state.enter) { enters.push(state); }
if (state.setup) { setups.push(state); }
}
for (i=0, l=enters.length; i<l; i++) {
enters[i].enter(this);
}
set(this, 'currentState', state);
for (i=0, l=setups.length; i<l; i++) {
setups[i].setup(this);
}
this.updateRecordArraysLater();
},
_unhandledEvent: function(state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + Ember.inspect(context) + ".";
}
throw new Ember.Error(errorMessage);
},
withTransaction: function(fn) {
var transaction = get(this, 'transaction');
if (transaction) { fn(transaction); }
},
/**
@method loadingData
@private
@param {Promise} promise
*/
loadingData: function(promise) {
this.send('loadingData', promise);
},
/**
@method loadedData
@private
*/
loadedData: function() {
this.send('loadedData');
},
/**
@method notFound
@private
*/
notFound: function() {
this.send('notFound');
},
/**
@method pushedData
@private
*/
pushedData: function() {
this.send('pushedData');
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollback()` a
delete after it was made.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
softDelete: function() {
this.get('model').deleteRecord();
},
confirm: function() {
this.get('model').save();
},
undo: function() {
this.get('model').rollback();
}
}
});
```
@method deleteRecord
*/
deleteRecord: function() {
this.send('deleteRecord');
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
this.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
@method destroyRecord
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord: function() {
this.deleteRecord();
return this.save();
},
/**
@method unloadRecord
@private
*/
unloadRecord: function() {
if (this.isDestroyed) { return; }
this.send('unloadRecord');
},
/**
@method clearRelationships
@private
*/
clearRelationships: function() {
this.eachRelationship(function(name, relationship) {
if (relationship.kind === 'belongsTo') {
set(this, name, null);
} else if (relationship.kind === 'hasMany') {
var hasMany = this._relationships[name];
if (hasMany) { // relationships are created lazily
hasMany.destroy();
}
}
}, this);
},
/**
@method updateRecordArrays
@private
*/
updateRecordArrays: function() {
this._updatingRecordArraysLater = false;
get(this, 'store').dataWasUpdated(this.constructor, this);
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
Example
```javascript
App.Mascot = DS.Model.extend({
name: attr('string')
});
var person = store.createRecord('person');
person.changedAttributes(); // {}
person.set('name', 'Tomster');
person.changedAttributes(); // {name: [undefined, 'Tomster']}
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes: function() {
var oldData = get(this, '_data'),
newData = get(this, '_attributes'),
diffData = {},
prop;
for (prop in newData) {
diffData[prop] = [oldData[prop], newData[prop]];
}
return diffData;
},
/**
@method adapterWillCommit
@private
*/
adapterWillCommit: function() {
this.send('willCommit');
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit: function(data) {
set(this, 'isError', false);
if (data) {
this._data = data;
} else {
Ember.mixin(this._data, this._inFlightAttributes);
}
this._inFlightAttributes = {};
this.send('didCommit');
this.updateRecordArraysLater();
if (!data) { return; }
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
/**
@method adapterDidDirty
@private
*/
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
dataDidChange: Ember.observer(function() {
this.reloadHasManys();
}, 'data'),
reloadHasManys: function() {
var relationships = get(this.constructor, 'relationshipsByName');
this.updateRecordArraysLater();
relationships.forEach(function(name, relationship) {
if (this._data.links && this._data.links[name]) { return; }
if (relationship.kind === 'hasMany') {
this.hasManyDidChange(relationship.key);
}
}, this);
},
hasManyDidChange: function(key) {
var hasMany = this._relationships[key];
if (hasMany) {
var records = this._data[key] || [];
set(hasMany, 'content', Ember.A(records));
set(hasMany, 'isLoaded', true);
hasMany.trigger('didLoad');
}
},
/**
@method updateRecordArraysLater
@private
*/
updateRecordArraysLater: function() {
// quick hack (something like this could be pushed into run.once
if (this._updatingRecordArraysLater) { return; }
this._updatingRecordArraysLater = true;
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
/**
@method setupData
@private
@param {Object} data
@param {Boolean} partial the data should be merged into
the existing data, not replace it.
*/
setupData: function(data, partial) {
if (partial) {
Ember.merge(this._data, data);
} else {
this._data = data;
}
var relationships = this._relationships;
this.eachRelationship(function(name, rel) {
if (data.links && data.links[name]) { return; }
if (rel.options.async) { relationships[name] = null; }
});
if (data) { this.pushedData(); }
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
materializeId: function(id) {
set(this, 'id', id);
},
materializeAttributes: function(attributes) {
Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes);
merge(this._data, attributes);
},
materializeAttribute: function(name, value) {
this._data[name] = value;
},
/**
@method updateHasMany
@private
@param {String} name
@param {Array} records
*/
updateHasMany: function(name, records) {
this._data[name] = records;
this.hasManyDidChange(name);
},
/**
@method updateBelongsTo
@private
@param {String} name
@param {DS.Model} record
*/
updateBelongsTo: function(name, record) {
this._data[name] = record;
},
/**
If the model `isDirty` this function will discard any unsaved
changes
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'
```
@method rollback
*/
rollback: function() {
this._attributes = {};
if (get(this, 'isError')) {
this._inFlightAttributes = {};
set(this, 'isError', false);
}
if (!get(this, 'isValid')) {
this._inFlightAttributes = {};
}
this.send('rolledBack');
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
toStringExtension: function() {
return get(this, 'id');
},
/**
The goal of this method is to temporarily disable specific observers
that take action in response to application changes.
This allows the system to make changes (such as materialization and
rollback) that should not trigger secondary behavior (such as setting an
inverse relationship or marking records as dirty).
The specific implementation will likely change as Ember proper provides
better infrastructure for suspending groups of observers, and if Array
observation becomes more unified with regular observers.
@method suspendRelationshipObservers
@private
@param callback
@param binding
*/
suspendRelationshipObservers: function(callback, binding) {
var observers = get(this.constructor, 'relationshipNames').belongsTo;
var self = this;
try {
this._suspendedRelationships = true;
Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() {
Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() {
callback.call(binding || self);
});
});
} finally {
this._suspendedRelationships = false;
}
},
/**
Save the record and persist any changes to the record to an
extenal source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function(){
// Success callback
}, function() {
// Error callback
});
```
@method save
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function() {
var promiseLabel = "DS: Model#save " + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.get('store').scheduleSave(this, resolver);
this._inFlightAttributes = this._attributes;
this._attributes = {};
return DS.PromiseObject.create({ promise: resolver.promise });
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
Example
```javascript
App.ModelViewRoute = Ember.Route.extend({
actions: {
reload: function() {
this.get('model').reload();
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload: function() {
set(this, 'isReloading', true);
var record = this;
var promiseLabel = "DS: Model#reload of " + this;
var promise = new Promise(function(resolve){
record.send('reloadRecord', resolve);
}, promiseLabel).then(function() {
record.set('isReloading', false);
record.set('isError', false);
return record;
}, function(reason) {
record.set('isError', true);
throw reason;
}, "DS: Model#reload complete, update flags");
return DS.PromiseObject.create({ promise: promise });
},
// FOR USE DURING COMMIT PROCESS
adapterDidUpdateAttribute: function(attributeName, value) {
// If a value is passed in, update the internal attributes and clear
// the attribute cache so it picks up the new value. Otherwise,
// collapse the current value into the internal attributes because
// the adapter has acknowledged it.
if (value !== undefined) {
this._data[attributeName] = value;
this.notifyPropertyChange(attributeName);
} else {
this._data[attributeName] = this._inFlightAttributes[attributeName];
}
this.updateRecordArraysLater();
},
/**
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate: function(errors) {
var recordErrors = get(this, 'errors');
function addError(name) {
if (errors[name]) {
recordErrors.add(name, errors[name]);
}
}
this.eachAttribute(addError);
this.eachRelationship(addError);
},
/**
@method adapterDidError
@private
*/
adapterDidError: function() {
this.send('becameError');
set(this, 'isError', true);
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param name
*/
trigger: function(name) {
Ember.tryInvoke(this, name, [].slice.call(arguments, 1));
this._super.apply(this, arguments);
},
triggerLater: function() {
if (this._deferredTriggers.push(arguments) !== 1) { return; }
Ember.run.schedule('actions', this, '_triggerDeferredTriggers');
},
_triggerDeferredTriggers: function() {
for (var i=0, l=this._deferredTriggers.length; i<l; i++) {
this.trigger.apply(this, this._deferredTriggers[i]);
}
this._deferredTriggers.length = 0;
},
willDestroy: function() {
this._super();
this.clearRelationships();
}
});
Model.reopenClass({
/**
Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model
instances from within the store, but if end users accidentally call `create()`
(instead of `createRecord()`), we can raise an error.
@method _create
@private
@static
*/
_create: Model.create,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
create: function() {
throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.");
}
});
__exports__["default"] = Model;
});
define("ember-data/lib/system/model/states",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
/*
This file encapsulates the various states that a record can transition
through during its lifecycle.
*/
/**
### State
Each record has a `currentState` property that explicitly tracks what
state a record is in at any given time. For instance, if a record is
newly created and has not yet been sent to the adapter to be saved,
it would be in the `root.loaded.created.uncommitted` state. If a
record has had local modifications made to it that are in the
process of being saved, the record would be in the
`root.loaded.updated.inFlight` state. (These state paths will be
explained in more detail below.)
Events are sent by the record or its store to the record's
`currentState` property. How the state reacts to these events is
dependent on which state it is in. In some states, certain events
will be invalid and will cause an exception to be raised.
States are hierarchical and every state is a substate of the
`RootState`. For example, a record can be in the
`root.deleted.uncommitted` state, then transition into the
`root.deleted.inFlight` state. If a child state does not implement
an event handler, the state manager will attempt to invoke the event
on all parent states until the root state is reached. The state
hierarchy of a record is described in terms of a path string. You
can determine a record's current state by getting the state's
`stateName` property:
```javascript
record.get('currentState.stateName');
//=> "root.created.uncommitted"
```
The hierarchy of valid states that ship with ember data looks like
this:
```text
* root
* deleted
* saved
* uncommitted
* inFlight
* empty
* loaded
* created
* uncommitted
* inFlight
* saved
* updated
* uncommitted
* inFlight
* loading
```
The `DS.Model` states are themselves stateless. What we mean is
that, the hierarchical states that each of *those* points to is a
shared data structure. For performance reasons, instead of each
record getting its own copy of the hierarchy of states, each record
points to this global, immutable shared instance. How does a state
know which record it should be acting on? We pass the record
instance into the state's event handlers as the first argument.
The record passed as the first parameter is where you should stash
state about the record if needed; you should never store data on the state
object itself.
### Events and Flags
A state may implement zero or more events and flags.
#### Events
Events are named functions that are invoked when sent to a record. The
record will first look for a method with the given name on the
current state. If no method is found, it will search the current
state's parent, and then its grandparent, and so on until reaching
the top of the hierarchy. If the root is reached without an event
handler being found, an exception will be raised. This can be very
helpful when debugging new features.
Here's an example implementation of a state with a `myEvent` event handler:
```javascript
aState: DS.State.create({
myEvent: function(manager, param) {
console.log("Received myEvent with", param);
}
})
```
To trigger this event:
```javascript
record.send('myEvent', 'foo');
//=> "Received myEvent with foo"
```
Note that an optional parameter can be sent to a record's `send()` method,
which will be passed as the second parameter to the event handler.
Events should transition to a different state if appropriate. This can be
done by calling the record's `transitionTo()` method with a path to the
desired state. The state manager will attempt to resolve the state path
relative to the current state. If no state is found at that path, it will
attempt to resolve it relative to the current state's parent, and then its
parent, and so on until the root is reached. For example, imagine a hierarchy
like this:
* created
* uncommitted <-- currentState
* inFlight
* updated
* inFlight
If we are currently in the `uncommitted` state, calling
`transitionTo('inFlight')` would transition to the `created.inFlight` state,
while calling `transitionTo('updated.inFlight')` would transition to
the `updated.inFlight` state.
Remember that *only events* should ever cause a state transition. You should
never call `transitionTo()` from outside a state's event handler. If you are
tempted to do so, create a new event and send that to the state manager.
#### Flags
Flags are Boolean values that can be used to introspect a record's current
state in a more user-friendly way than examining its state path. For example,
instead of doing this:
```javascript
var statePath = record.get('stateManager.currentPath');
if (statePath === 'created.inFlight') {
doSomething();
}
```
You can say:
```javascript
if (record.get('isNew') && record.get('isSaving')) {
doSomething();
}
```
If your state does not set a value for a given flag, the value will
be inherited from its parent (or the first place in the state hierarchy
where it is defined).
The current set of flags are defined below. If you want to add a new flag,
in addition to the area below, you will also need to declare it in the
`DS.Model` class.
* [isEmpty](DS.Model.html#property_isEmpty)
* [isLoading](DS.Model.html#property_isLoading)
* [isLoaded](DS.Model.html#property_isLoaded)
* [isDirty](DS.Model.html#property_isDirty)
* [isSaving](DS.Model.html#property_isSaving)
* [isDeleted](DS.Model.html#property_isDeleted)
* [isNew](DS.Model.html#property_isNew)
* [isValid](DS.Model.html#property_isValid)
@namespace DS
@class RootState
*/
function hasDefinedProperties(object) {
// Ignore internal property defined by simulated `Ember.create`.
var names = Ember.keys(object);
var i, l, name;
for (i = 0, l = names.length; i < l; i++ ) {
name = names[i];
if (object.hasOwnProperty(name) && object[name]) { return true; }
}
return false;
}
function didSetProperty(record, context) {
if (context.value === context.originalValue) {
delete record._attributes[context.name];
record.send('propertyWasReset', context.name);
} else if (context.value !== context.oldValue) {
record.send('becomeDirty');
}
record.updateRecordArraysLater();
}
// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
// record is loaded via `store.find`, `isLoaded` is false
// until the adapter sets it. When a record is created locally,
// its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
// saved by the adapter. This includes records that have been
// created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
// the adapter has not yet acknowledged that the changes have
// been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
// is true and `isDirty` is true, the record is deleted locally
// but the deletion was not yet persisted. When `isSaving` is
// true, the change is in-flight. When both `isDirty` and
// `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
// local changes to the backend. This may also result in the
// record having its `isValid` property become false if the
// adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
// did not yet report that it was successfully saved.
// * isValid: No client-side validations have failed and the
// adapter did not report any server-side validation failures.
// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
// to be saved.
// `inFlight`: the store has handed off the record to be saved,
// but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
// send to the adapter yet.
var DirtyState = {
initialState: 'uncommitted',
// FLAGS
isDirty: true,
// SUBSTATES
// When a record first becomes dirty, it is `uncommitted`.
// This means that there are local pending changes, but they
// have not yet begun to be saved, and are not invalid.
uncommitted: {
// EVENTS
didSetProperty: didSetProperty,
propertyWasReset: function(record, name) {
var stillDirty = false;
for (var prop in record._attributes) {
stillDirty = true;
break;
}
if (!stillDirty) { record.send('rolledBack'); }
},
pushedData: Ember.K,
becomeDirty: Ember.K,
willCommit: function(record) {
record.transitionTo('inFlight');
},
reloadRecord: function(record, resolve) {
resolve(get(record, 'store').reloadRecord(record));
},
rolledBack: function(record) {
record.transitionTo('loaded.saved');
},
becameInvalid: function(record) {
record.transitionTo('invalid');
},
rollback: function(record) {
record.rollback();
}
},
// Once a record has been handed off to the adapter to be
// saved, it is in the 'in flight' state. Changes to the
// record cannot be made during this window.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
didSetProperty: didSetProperty,
becomeDirty: Ember.K,
pushedData: Ember.K,
unloadRecord: function(record) {
Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + " `", false);
},
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
var dirtyType = get(this, 'dirtyType');
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks', dirtyType);
},
becameInvalid: function(record) {
record.transitionTo('invalid');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// A record is in the `invalid` state when its client-side
// invalidations have failed, or if the adapter has indicated
// the the record failed server-side invalidations.
invalid: {
// FLAGS
isValid: false,
// EVENTS
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
},
didSetProperty: function(record, context) {
get(record, 'errors').remove(context.name);
didSetProperty(record, context);
},
becomeDirty: Ember.K,
rolledBack: function(record) {
get(record, 'errors').clear();
},
becameValid: function(record) {
record.transitionTo('uncommitted');
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('becameInvalid', record);
}
}
};
// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.
function deepClone(object) {
var clone = {}, value;
for (var prop in object) {
value = object[prop];
if (value && typeof value === 'object') {
clone[prop] = deepClone(value);
} else {
clone[prop] = value;
}
}
return clone;
}
function mixin(original, hash) {
for (var prop in hash) {
original[prop] = hash[prop];
}
return original;
}
function dirtyState(options) {
var newState = deepClone(DirtyState);
return mixin(newState, options);
}
var createdState = dirtyState({
dirtyType: 'created',
// FLAGS
isNew: true
});
createdState.uncommitted.rolledBack = function(record) {
record.transitionTo('deleted.saved');
};
var updatedState = dirtyState({
dirtyType: 'updated'
});
createdState.uncommitted.deleteRecord = function(record) {
record.clearRelationships();
record.transitionTo('deleted.saved');
};
createdState.uncommitted.rollback = function(record) {
DirtyState.uncommitted.rollback.apply(this, arguments);
record.transitionTo('deleted.saved');
};
createdState.uncommitted.propertyWasReset = Ember.K;
function assertAgainstUnloadRecord(record) {
Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + "`", false);
}
updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord;
updatedState.uncommitted.deleteRecord = function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
};
var RootState = {
// FLAGS
isEmpty: false,
isLoading: false,
isLoaded: false,
isDirty: false,
isSaving: false,
isDeleted: false,
isNew: false,
isValid: true,
// DEFAULT EVENTS
// Trying to roll back if you're not in the dirty state
// doesn't change your state. For example, if you're in the
// in-flight state, rolling back the record doesn't move
// you out of the in-flight state.
rolledBack: Ember.K,
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
propertyWasReset: Ember.K,
// SUBSTATES
// A record begins its lifecycle in the `empty` state.
// If its data will come from the adapter, it will
// transition into the `loading` state. Otherwise, if
// the record is being created on the client, it will
// transition into the `created` state.
empty: {
isEmpty: true,
// EVENTS
loadingData: function(record, promise) {
record._loadingPromise = promise;
record.transitionTo('loading');
},
loadedData: function(record) {
record.transitionTo('loaded.created.uncommitted');
record.suspendRelationshipObservers(function() {
record.notifyPropertyChange('data');
});
},
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
}
},
// A record enters this state when the store asks
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: {
// FLAGS
isLoading: true,
exit: function(record) {
record._loadingPromise = null;
},
// EVENTS
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
set(record, 'isError', false);
},
becameError: function(record) {
record.triggerLater('becameError', record);
},
notFound: function(record) {
record.transitionTo('empty');
}
},
// A record enters this state when its data is populated.
// Most of a record's lifecycle is spent inside substates
// of the `loaded` state.
loaded: {
initialState: 'saved',
// FLAGS
isLoaded: true,
// SUBSTATES
// If there are no local changes to a record, it remains
// in the `saved` state.
saved: {
setup: function(record) {
var attrs = record._attributes,
isDirty = false;
for (var prop in attrs) {
if (attrs.hasOwnProperty(prop)) {
isDirty = true;
break;
}
}
if (isDirty) {
record.adapterDidDirty();
}
},
// EVENTS
didSetProperty: didSetProperty,
pushedData: Ember.K,
becomeDirty: function(record) {
record.transitionTo('updated.uncommitted');
},
willCommit: function(record) {
record.transitionTo('updated.inFlight');
},
reloadRecord: function(record, resolve) {
resolve(get(record, 'store').reloadRecord(record));
},
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
},
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
didCommit: function(record) {
record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType'));
},
// loaded.saved.notFound would be triggered by a failed
// `reload()` on an unchanged record
notFound: Ember.K
},
// A record is in this state after it has been locally
// created but before the adapter has indicated that
// it has been saved.
created: createdState,
// A record is in this state if it has already been
// saved to the server, but there are new local changes
// that have not yet been saved.
updated: updatedState
},
// A record is in this state if it was deleted from the store.
deleted: {
initialState: 'uncommitted',
dirtyType: 'deleted',
// FLAGS
isDeleted: true,
isLoaded: true,
isDirty: true,
// TRANSITIONS
setup: function(record) {
record.updateRecordArrays();
},
// SUBSTATES
// When a record is deleted, it enters the `start`
// state. It will exit this state when the record
// starts to commit.
uncommitted: {
// EVENTS
willCommit: function(record) {
record.transitionTo('inFlight');
},
rollback: function(record) {
record.rollback();
},
becomeDirty: Ember.K,
deleteRecord: Ember.K,
rolledBack: function(record) {
record.transitionTo('loaded.saved');
}
},
// After a record starts committing, but
// before the adapter indicates that the deletion
// has saved to the server, a record is in the
// `inFlight` substate of `deleted`.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
unloadRecord: assertAgainstUnloadRecord,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// Once the adapter indicates that the deletion has
// been saved, the record enters the `saved` substate
// of `deleted`.
saved: {
// FLAGS
isDirty: false,
setup: function(record) {
var store = get(record, 'store');
store.dematerializeRecord(record);
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('didDelete', record);
record.triggerLater('didCommit', record);
}
}
},
invokeLifecycleCallbacks: function(record, dirtyType) {
if (dirtyType === 'created') {
record.triggerLater('didCreate', record);
} else {
record.triggerLater('didUpdate', record);
}
record.triggerLater('didCommit', record);
}
};
function wireState(object, parent, name) {
/*jshint proto:true*/
// TODO: Use Object.create and copy instead
object = mixin(parent ? Ember.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
for (var prop in object) {
if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; }
if (typeof object[prop] === 'object') {
object[prop] = wireState(object[prop], object, name + "." + prop);
}
}
return object;
}
RootState = wireState(RootState, null, "root");
__exports__["default"] = RootState;
});
define("ember-data/lib/system/record_array_manager",
["./record_arrays","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var ManyArray = __dependency1__.ManyArray;
var get = Ember.get, set = Ember.set;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RecordArrayManager
@namespace DS
@private
@extends Ember.Object
*/
var RecordArrayManager = Ember.Object.extend({
init: function() {
this.filteredRecordArrays = Ember.MapWithDefault.create({
defaultValue: function() { return []; }
});
this.changedRecords = [];
this._adapterPopulatedRecordArrays = [];
},
recordDidChange: function(record) {
if (this.changedRecords.push(record) !== 1) { return; }
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
recordArraysForRecord: function(record) {
record._recordArrays = record._recordArrays || Ember.OrderedSet.create();
return record._recordArrays;
},
/**
This method is invoked whenever data is loaded into the store by the
adapter or updated by the adapter, or when a record has changed.
It updates all record arrays that a record belongs to.
To avoid thrashing, it only runs at most once per run loop.
@method updateRecordArrays
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArrays: function() {
forEach(this.changedRecords, function(record) {
if (get(record, 'isDeleted')) {
this._recordWasDeleted(record);
} else {
this._recordWasChanged(record);
}
}, this);
this.changedRecords.length = 0;
},
_recordWasDeleted: function (record) {
var recordArrays = record._recordArrays;
if (!recordArrays) { return; }
forEach(recordArrays, function(array) {
array.removeRecord(record);
});
},
_recordWasChanged: function (record) {
var type = record.constructor,
recordArrays = this.filteredRecordArrays.get(type),
filter;
forEach(recordArrays, function(array) {
filter = get(array, 'filterFunction');
this.updateRecordArray(array, filter, type, record);
}, this);
// loop through all manyArrays containing an unloaded copy of this
// clientId and notify them that the record was loaded.
var manyArrays = record._loadingRecordArrays;
if (manyArrays) {
for (var i=0, l=manyArrays.length; i<l; i++) {
manyArrays[i].loadedRecord();
}
record._loadingRecordArrays = [];
}
},
/**
Update an individual filter.
@method updateRecordArray
@param {DS.FilteredRecordArray} array
@param {Function} filter
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArray: function(array, filter, type, record) {
var shouldBeInArray;
if (!filter) {
shouldBeInArray = true;
} else {
shouldBeInArray = filter(record);
}
var recordArrays = this.recordArraysForRecord(record);
if (shouldBeInArray) {
recordArrays.add(array);
array.addRecord(record);
} else if (!shouldBeInArray) {
recordArrays.remove(array);
array.removeRecord(record);
}
},
/**
This method is invoked if the `filterFunction` property is
changed on a `DS.FilteredRecordArray`.
It essentially re-runs the filter from scratch. This same
method is invoked when the filter is created in th first place.
@method updateFilter
@param array
@param type
@param filter
*/
updateFilter: function(array, type, filter) {
var typeMap = this.store.typeMapFor(type),
records = typeMap.records, record;
for (var i=0, l=records.length; i<l; i++) {
record = records[i];
if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) {
this.updateRecordArray(array, filter, type, record);
}
}
},
/**
Create a `DS.ManyArray` for a type and list of record references, and index
the `ManyArray` under each reference. This allows us to efficiently remove
records from `ManyArray`s when they are deleted.
@method createManyArray
@param {Class} type
@param {Array} references
@return {DS.ManyArray}
*/
createManyArray: function(type, records) {
var manyArray = ManyArray.create({
type: type,
content: records,
store: this.store
});
forEach(records, function(record) {
var arrays = this.recordArraysForRecord(record);
arrays.add(manyArray);
}, this);
return manyArray;
},
/**
Create a `DS.RecordArray` for a type and register it for updates.
@method createRecordArray
@param {Class} type
@return {DS.RecordArray}
*/
createRecordArray: function(type) {
var array = DS.RecordArray.create({
type: type,
content: Ember.A(),
store: this.store,
isLoaded: true
});
this.registerFilteredRecordArray(array, type);
return array;
},
/**
Create a `DS.FilteredRecordArray` for a type and register it for updates.
@method createFilteredRecordArray
@param {Class} type
@param {Function} filter
@return {DS.FilteredRecordArray}
*/
createFilteredRecordArray: function(type, filter) {
var array = DS.FilteredRecordArray.create({
type: type,
content: Ember.A(),
store: this.store,
manager: this,
filterFunction: filter
});
this.registerFilteredRecordArray(array, type, filter);
return array;
},
/**
Create a `DS.AdapterPopulatedRecordArray` for a type with given query.
@method createAdapterPopulatedRecordArray
@param {Class} type
@param {Object} query
@return {DS.AdapterPopulatedRecordArray}
*/
createAdapterPopulatedRecordArray: function(type, query) {
var array = DS.AdapterPopulatedRecordArray.create({
type: type,
query: query,
content: Ember.A(),
store: this.store
});
this._adapterPopulatedRecordArrays.push(array);
return array;
},
/**
Register a RecordArray for a given type to be backed by
a filter function. This will cause the array to update
automatically when records of that type change attribute
values or states.
@method registerFilteredRecordArray
@param {DS.RecordArray} array
@param {Class} type
@param {Function} filter
*/
registerFilteredRecordArray: function(array, type, filter) {
var recordArrays = this.filteredRecordArrays.get(type);
recordArrays.push(array);
this.updateFilter(array, type, filter);
},
// Internally, we maintain a map of all unloaded IDs requested by
// a ManyArray. As the adapter loads data into the store, the
// store notifies any interested ManyArrays. When the ManyArray's
// total number of loading records drops to zero, it becomes
// `isLoaded` and fires a `didLoad` event.
registerWaitingRecordArray: function(record, array) {
var loadingRecordArrays = record._loadingRecordArrays || [];
loadingRecordArrays.push(array);
record._loadingRecordArrays = loadingRecordArrays;
},
willDestroy: function(){
this._super();
flatten(values(this.filteredRecordArrays.values)).forEach(destroy);
this._adapterPopulatedRecordArrays.forEach(destroy);
}
});
function values(obj) {
var result = [];
var keys = Ember.keys(obj);
for (var i = 0; i < keys.length; i++) {
result.push(obj[keys[i]]);
}
return result;
}
function destroy(entry) {
entry.destroy();
}
function flatten(list) {
var length = list.length;
var result = Ember.A();
for (var i = 0; i < length; i++) {
result = result.concat(list[i]);
}
return result;
}
__exports__["default"] = RecordArrayManager;
});
define("ember-data/lib/system/record_arrays",
["./record_arrays/record_array","./record_arrays/filtered_record_array","./record_arrays/adapter_populated_record_array","./record_arrays/many_array","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
/**
@module ember-data
*/
var RecordArray = __dependency1__["default"];
var FilteredRecordArray = __dependency2__["default"];
var AdapterPopulatedRecordArray = __dependency3__["default"];
var ManyArray = __dependency4__["default"];
__exports__.RecordArray = RecordArray;
__exports__.FilteredRecordArray = FilteredRecordArray;
__exports__.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray;
__exports__.ManyArray = ManyArray;
});
define("ember-data/lib/system/record_arrays/adapter_populated_record_array",
["./record_array","exports"],
function(__dependency1__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
/**
Represents an ordered list of records whose order and membership is
determined by the adapter. For example, a query sent to the adapter
may trigger a search on the server, whose results would be loaded
into an instance of the `AdapterPopulatedRecordArray`.
@class AdapterPopulatedRecordArray
@namespace DS
@extends DS.RecordArray
*/
var AdapterPopulatedRecordArray = RecordArray.extend({
query: null,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a server query (on " + type + ") is immutable.");
},
/**
@method load
@private
@param {Array} data
*/
load: function(data) {
var store = get(this, 'store'),
type = get(this, 'type'),
records = store.pushMany(type, data),
meta = store.metadataFor(type);
this.setProperties({
content: Ember.A(records),
isLoaded: true,
meta: meta
});
// TODO: should triggering didLoad event be the last action of the runLoop?
Ember.run.once(this, 'trigger', 'didLoad');
}
});
__exports__["default"] = AdapterPopulatedRecordArray;
});
define("ember-data/lib/system/record_arrays/filtered_record_array",
["./record_array","exports"],
function(__dependency1__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get;
/**
Represents a list of records whose membership is determined by the
store. As records are created, loaded, or modified, the store
evaluates them to determine if they should be part of the record
array.
@class FilteredRecordArray
@namespace DS
@extends DS.RecordArray
*/
var FilteredRecordArray = RecordArray.extend({
/**
The filterFunction is a function used to test records from the store to
determine if they should be part of the record array.
Example
```javascript
var allPeople = store.all('person');
allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"]
var people = store.filter('person', function(person) {
if (person.get('name').match(/Katz$/)) { return true; }
});
people.mapBy('name'); // ["Yehuda Katz"]
var notKatzFilter = function(person) {
return !person.get('name').match(/Katz$/);
};
people.set('filterFunction', notKatzFilter);
people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"]
```
@method filterFunction
@param {DS.Model} record
@return {Boolean} `true` if the record should be in the array
*/
filterFunction: null,
isLoaded: true,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
/**
@method updateFilter
@private
*/
updateFilter: Ember.observer(function() {
var manager = get(this, 'manager');
manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction'));
}, 'filterFunction')
});
__exports__["default"] = FilteredRecordArray;
});
define("ember-data/lib/system/record_arrays/many_array",
["./record_array","../changes","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
var RelationshipChange = __dependency2__.RelationshipChange;
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var map = Ember.EnumerableUtils.map;
function sync(change) {
change.sync();
}
/**
A `ManyArray` is a `RecordArray` that represents the contents of a has-many
relationship.
The `ManyArray` is instantiated lazily the first time the relationship is
requested.
### Inverses
Often, the relationships in Ember Data applications will have
an inverse. For example, imagine the following models are
defined:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
If you created a new instance of `App.Post` and added
a `App.Comment` record to its `comments` has-many
relationship, you would expect the comment's `post`
property to be set to the post that contained
the has-many.
We call the record to which a relationship belongs the
relationship's _owner_.
@class ManyArray
@namespace DS
@extends DS.RecordArray
*/
var ManyArray = RecordArray.extend({
init: function() {
this._super.apply(this, arguments);
this._changesToSync = Ember.OrderedSet.create();
},
/**
The property name of the relationship
@property {String} name
@private
*/
name: null,
/**
The record to which this relationship belongs.
@property {DS.Model} owner
@private
*/
owner: null,
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean} isPolymorphic
@private
*/
isPolymorphic: false,
// LOADING STATE
isLoaded: false,
/**
Used for async `hasMany` arrays
to keep track of when they will resolve.
@property {Ember.RSVP.Promise} promise
@private
*/
promise: null,
/**
@method loadingRecordsCount
@param {Number} count
@private
*/
loadingRecordsCount: function(count) {
this.loadingRecordsCount = count;
},
/**
@method loadedRecord
@private
*/
loadedRecord: function() {
this.loadingRecordsCount--;
if (this.loadingRecordsCount === 0) {
set(this, 'isLoaded', true);
this.trigger('didLoad');
}
},
/**
@method fetch
@private
*/
fetch: function() {
var records = get(this, 'content'),
store = get(this, 'store'),
owner = get(this, 'owner'),
resolver = Ember.RSVP.defer("DS: ManyArray#fetch " + get(this, 'type'));
var unloadedRecords = records.filterProperty('isEmpty', true);
store.fetchMany(unloadedRecords, owner, resolver);
},
// Overrides Ember.Array's replace method to implement
replaceContent: function(index, removed, added) {
// Map the array of record objects into an array of client ids.
added = map(added, function(record) {
Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.type.typeKey + "' allowed)", !this.type || record instanceof this.type);
return record;
}, this);
this._super(index, removed, added);
},
arrangedContentDidChange: function() {
Ember.run.once(this, 'fetch');
},
arrayContentWillChange: function(index, removed, added) {
var owner = get(this, 'owner'),
name = get(this, 'name');
if (!owner._suspendedRelationships) {
// This code is the first half of code that continues inside
// of arrayContentDidChange. It gets or creates a change from
// the child object, adds the current owner as the old
// parent if this is the first time the object was removed
// from a ManyArray, and sets `newParent` to null.
//
// Later, if the object is added to another ManyArray,
// the `arrayContentDidChange` will set `newParent` on
// the change.
for (var i=index; i<index+removed; i++) {
var record = get(this, 'content').objectAt(i);
var change = RelationshipChange.createChange(owner, record, get(this, 'store'), {
parentType: owner.constructor,
changeType: "remove",
kind: "hasMany",
key: name
});
this._changesToSync.add(change);
}
}
return this._super.apply(this, arguments);
},
arrayContentDidChange: function(index, removed, added) {
this._super.apply(this, arguments);
var owner = get(this, 'owner'),
name = get(this, 'name'),
store = get(this, 'store');
if (!owner._suspendedRelationships) {
// This code is the second half of code that started in
// `arrayContentWillChange`. It gets or creates a change
// from the child object, and adds the current owner as
// the new parent.
for (var i=index; i<index+added; i++) {
var record = get(this, 'content').objectAt(i);
var change = RelationshipChange.createChange(owner, record, store, {
parentType: owner.constructor,
changeType: "add",
kind:"hasMany",
key: name
});
change.hasManyName = name;
this._changesToSync.add(change);
}
// We wait until the array has finished being
// mutated before syncing the OneToManyChanges created
// in arrayContentWillChange, so that the array
// membership test in the sync() logic operates
// on the final results.
this._changesToSync.forEach(sync);
this._changesToSync.clear();
}
},
/**
Create a child record within the owner
@method createRecord
@private
@param {Object} hash
@return {DS.Model} record
*/
createRecord: function(hash) {
var owner = get(this, 'owner'),
store = get(owner, 'store'),
type = get(this, 'type'),
record;
Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic'));
record = store.createRecord.call(store, type, hash);
this.pushObject(record);
return record;
}
});
__exports__["default"] = ManyArray;
});
define("ember-data/lib/system/record_arrays/record_array",
["../store","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var PromiseArray = __dependency1__.PromiseArray;
var get = Ember.get, set = Ember.set;
/**
A record array is an array that contains records of a certain type. The record
array materializes records as needed when they are retrieved for the first
time. You should not create record arrays yourself. Instead, an instance of
`DS.RecordArray` or its subclasses will be returned by your application's store
in response to queries.
@class RecordArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.Evented
*/
var RecordArray = Ember.ArrayProxy.extend(Ember.Evented, {
/**
The model type contained by this record array.
@property type
@type DS.Model
*/
type: null,
/**
The array of client ids backing the record array. When a
record is requested from the record array, the record
for the client id at the same index is materialized, if
necessary, by the store.
@property content
@private
@type Ember.Array
*/
content: null,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all(App.Person);
people.get('isLoaded'); // true
```
@property isLoaded
@type Boolean
*/
isLoaded: false,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all(App.Person);
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@property isUpdating
@type Boolean
*/
isUpdating: false,
/**
The store that created this record array.
@property store
@private
@type DS.Store
*/
store: null,
/**
Retrieves an object from the content by index.
@method objectAtContent
@private
@param {Number} index
@return {DS.Model} record
*/
objectAtContent: function(index) {
var content = get(this, 'content');
return content.objectAt(index);
},
/**
Used to get the latest version of all of the records in this array
from the adapter.
Example
```javascript
var people = store.all(App.Person);
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@method update
*/
update: function() {
if (get(this, 'isUpdating')) { return; }
var store = get(this, 'store'),
type = get(this, 'type');
return store.fetchAll(type, this);
},
/**
Adds a record to the `RecordArray`.
@method addRecord
@private
@param {DS.Model} record
*/
addRecord: function(record) {
get(this, 'content').addObject(record);
},
/**
Removes a record to the `RecordArray`.
@method removeRecord
@private
@param {DS.Model} record
*/
removeRecord: function(record) {
get(this, 'content').removeObject(record);
},
/**
Saves all of the records in the `RecordArray`.
Example
```javascript
var messages = store.all(App.Message);
messages.forEach(function(message) {
message.set('hasBeenSeen', true);
});
messages.save();
```
@method save
@return {DS.PromiseArray} promise
*/
save: function() {
var promiseLabel = "DS: RecordArray#save " + get(this, 'type');
var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) {
return Ember.A(array);
}, null, "DS: RecordArray#save apply Ember.NativeArray");
return PromiseArray.create({ promise: promise });
},
_dissociateFromOwnRecords: function() {
var array = this;
this.forEach(function(record){
var recordArrays = record._recordArrays;
if (recordArrays) {
recordArrays.remove(array);
}
});
},
willDestroy: function(){
this._dissociateFromOwnRecords();
this._super();
}
});
__exports__["default"] = RecordArray;
});
define("ember-data/lib/system/relationships",
["./relationships/belongs_to","./relationships/has_many","../system/relationships/ext","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
/**
@module ember-data
*/
var belongsTo = __dependency1__["default"];
var hasMany = __dependency2__["default"];
__exports__.belongsTo = belongsTo;
__exports__.hasMany = hasMany;
});
define("ember-data/lib/system/relationships/belongs_to",
["../model","exports"],
function(__dependency1__, __exports__) {
"use strict";
var get = Ember.get, set = Ember.set,
isNone = Ember.isNone;
var Promise = Ember.RSVP.Promise;
var Model = __dependency1__.Model;
/**
@module ember-data
*/
function asyncBelongsTo(type, options, meta) {
return Ember.computed('data', function(key, value) {
var data = get(this, 'data'),
store = get(this, 'store'),
promiseLabel = "DS: Async belongsTo " + this + " : " + key,
promise;
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof store.modelFor(type));
return value === undefined ? null : DS.PromiseObject.create({
promise: Promise.cast(value, promiseLabel)
});
}
var link = data.links && data.links[key],
belongsTo = data[key];
if(!isNone(belongsTo)) {
promise = store.fetchRecord(belongsTo) || Promise.cast(belongsTo, promiseLabel);
return DS.PromiseObject.create({
promise: promise
});
} else if (link) {
promise = store.findBelongsTo(this, link, meta);
return DS.PromiseObject.create({
promise: promise
});
} else {
return null;
}
}).meta(meta);
}
/**
`DS.belongsTo` is used to define One-To-One and One-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.belongsTo` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a
related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses)
#### One-To-One
To declare a one-to-one relationship between two models, use
`DS.belongsTo`:
```javascript
App.User = DS.Model.extend({
profile: DS.belongsTo('profile')
});
App.Profile = DS.Model.extend({
user: DS.belongsTo('user')
});
```
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
@namespace
@method belongsTo
@for DS
@param {String or DS.Model} type the model type of the relationship
@param {Object} options a hash of options
@return {Ember.computed} relationship
*/
function belongsTo(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
} else {
Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type)));
}
options = options || {};
var meta = {
type: type,
isRelationship: true,
options: options,
kind: 'belongsTo'
};
if (options.async) {
return asyncBelongsTo(type, options, meta);
}
return Ember.computed('data', function(key, value) {
var data = get(this, 'data'),
store = get(this, 'store'), belongsTo, typeClass;
if (typeof type === 'string') {
typeClass = store.modelFor(type);
} else {
typeClass = type;
}
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass);
return value === undefined ? null : value;
}
belongsTo = data[key];
if (isNone(belongsTo)) { return null; }
store.fetchRecord(belongsTo);
return belongsTo;
}).meta(meta);
}
/**
These observers observe all `belongsTo` relationships on the record. See
`relationships/ext` to see how these observers get their dependencies.
@class Model
@namespace DS
*/
Model.reopen({
/**
@method belongsToWillChange
@private
@static
@param record
@param key
*/
belongsToWillChange: Ember.beforeObserver(function(record, key) {
if (get(record, 'isLoaded')) {
var oldParent = get(record, key);
if (oldParent) {
var store = get(record, 'store'),
change = DS.RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" });
change.sync();
this._changesToSync[key] = change;
}
}
}),
/**
@method belongsToDidChange
@private
@static
@param record
@param key
*/
belongsToDidChange: Ember.immediateObserver(function(record, key) {
if (get(record, 'isLoaded')) {
var newParent = get(record, key);
if (newParent) {
var store = get(record, 'store'),
change = DS.RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" });
change.sync();
}
}
delete this._changesToSync[key];
})
});
__exports__["default"] = belongsTo;
});
define("ember-data/lib/system/relationships/ext",
["../../../../ember-inflector/lib/system","../model"],
function(__dependency1__, __dependency2__) {
"use strict";
var singularize = __dependency1__.singularize;
var Model = __dependency2__.Model;
var get = Ember.get, set = Ember.set;
/**
@module ember-data
*/
/*
This file defines several extensions to the base `DS.Model` class that
add support for one-to-many relationships.
*/
/**
@class Model
@namespace DS
*/
Model.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param proto
@param key
@param value
*/
didDefineProperty: function(proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.Descriptor) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
if (meta.isRelationship && meta.kind === 'belongsTo') {
Ember.addObserver(proto, key, null, 'belongsToDidChange');
Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange');
}
meta.parentType = proto.constructor;
}
}
});
/*
These DS.Model extensions add class methods that provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
Model.reopenClass({
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@return {subclass of DS.Model} the type of the relationship, or undefined
*/
typeForRelationship: function(name) {
var relationship = get(this, 'relationshipsByName').get(name);
return relationship && relationship.type;
},
inverseFor: function(name) {
var inverseType = this.typeForRelationship(name);
if (!inverseType) { return null; }
var options = this.metaForProperty(name).options;
if (options.inverse === null) { return null; }
var inverseName, inverseKind;
if (options.inverse) {
inverseName = options.inverse;
inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind;
} else {
var possibleRelationships = findPossibleInverses(this, inverseType);
if (possibleRelationships.length === 0) { return null; }
Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1);
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
function findPossibleInverses(type, inverseType, possibleRelationships) {
possibleRelationships = possibleRelationships || [];
var relationshipMap = get(inverseType, 'relationships');
if (!relationshipMap) { return; }
var relationships = relationshipMap.get(type);
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type));
}
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, possibleRelationships);
}
return possibleRelationships;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
var relationships = Ember.get(App.Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: Ember.computed(function() {
var map = new Ember.MapWithDefault({
defaultValue: function() { return []; }
});
// Loop through each computed property on the class
this.eachComputedProperty(function(name, meta) {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
if (typeof meta.type === 'string') {
meta.type = this.store.modelFor(meta.type);
}
var relationshipsForType = map.get(meta.type);
relationshipsForType.push({ name: name, kind: meta.kind });
}
});
return map;
}),
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipNames = Ember.get(App.Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function() {
var names = { hasMany: [], belongsTo: [] };
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relatedTypes = Ember.get(App.Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: Ember.computed(function() {
var type,
types = Ember.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
type = meta.type;
if (typeof type === 'string') {
type = get(this, type, false) || this.store.modelFor(type);
}
Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type);
if (!types.contains(type)) {
Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type);
types.push(type);
}
}
});
return types;
}),
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: Ember.computed(function() {
var map = Ember.Map.create(), type;
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
meta.key = name;
type = meta.type;
if (!type && meta.kind === 'hasMany') {
type = singularize(name);
} else if (!type) {
type = name;
}
if (typeof type === 'string') {
meta.type = this.store.modelFor(type);
}
map.set(name, meta);
}
});
return map;
}),
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
var fields = Ember.get(App.Blog, 'fields');
fields.forEach(function(field, kind) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
get(this, 'relationshipsByName').forEach(function(name, relationship) {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType: function(callback, binding) {
get(this, 'relatedTypes').forEach(function(type) {
callback.call(binding, type);
});
}
});
Model.reopen({
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
this.constructor.eachRelationship(callback, binding);
}
});
});
define("ember-data/lib/system/relationships/has_many",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties;
function asyncHasMany(type, options, meta) {
return Ember.computed('data', function(key) {
var relationship = this._relationships[key],
promiseLabel = "DS: Async hasMany " + this + " : " + key;
if (!relationship) {
var resolver = Ember.RSVP.defer(promiseLabel);
relationship = buildRelationship(this, key, options, function(store, data) {
var link = data.links && data.links[key];
var rel;
if (link) {
rel = store.findHasMany(this, link, meta, resolver);
} else {
rel = store.findMany(this, data[key], meta.type, resolver);
}
// cache the promise so we can use it
// when we come back and don't need to rebuild
// the relationship.
set(rel, 'promise', resolver.promise);
return rel;
});
}
var promise = relationship.get('promise').then(function() {
return relationship;
}, null, "DS: Async hasMany records received");
return DS.PromiseArray.create({
promise: promise
});
}).meta(meta).readOnly();
}
function buildRelationship(record, key, options, callback) {
var rels = record._relationships;
if (rels[key]) { return rels[key]; }
var data = get(record, 'data'),
store = get(record, 'store');
var relationship = rels[key] = callback.call(record, store, data);
return setProperties(relationship, {
owner: record,
name: key,
isPolymorphic: options.polymorphic
});
}
function hasRelationship(type, options) {
options = options || {};
var meta = {
type: type,
isRelationship: true,
options: options,
kind: 'hasMany'
};
if (options.async) {
return asyncHasMany(type, options, meta);
}
return Ember.computed('data', function(key) {
return buildRelationship(this, key, options, function(store, data) {
var records = data[key];
Ember.assert("You looked up the '" + key + "' relationship on '" + this + "' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", Ember.A(records).everyProperty('isEmpty', false));
return store.findMany(this, data[key], meta.type);
});
}).meta(meta).readOnly();
}
/**
`DS.hasMany` is used to define One-To-Many and Many-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.hasMany` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a related model.
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
#### Many-To-Many
To declare a many-to-many relationship between two models, use
`DS.hasMany`:
```javascript
App.Post = DS.Model.extend({
tags: DS.hasMany('tag')
});
App.Tag = DS.Model.extend({
posts: DS.hasMany('post')
});
```
#### Explicit Inverses
Ember Data will do its best to discover which relationships map to
one another. In the one-to-many code above, for example, Ember Data
can figure out that changing the `comments` relationship should update
the `post` relationship on the inverse because post is the only
relationship to that model.
However, sometimes you may have multiple `belongsTo`/`hasManys` for the
same type. You can specify which property on the related model is
the inverse using `DS.hasMany`'s `inverse` option:
```javascript
var belongsTo = DS.belongsTo,
hasMany = DS.hasMany;
App.Comment = DS.Model.extend({
onePost: belongsTo('post'),
twoPost: belongsTo('post'),
redPost: belongsTo('post'),
bluePost: belongsTo('post')
});
App.Post = DS.Model.extend({
comments: hasMany('comment', {
inverse: 'redPost'
})
});
```
You can also specify an inverse on a `belongsTo`, which works how
you'd expect.
@namespace
@method hasMany
@for DS
@param {String or DS.Model} type the model type of the relationship
@param {Object} options a hash of options
@return {Ember.computed} relationship
*/
function hasMany(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
}
return hasRelationship(type, options);
}
__exports__["default"] = hasMany;
});
define("ember-data/lib/system/store",
["exports"],
function(__exports__) {
"use strict";
/*globals Ember*/
/*jshint eqnull:true*/
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var once = Ember.run.once;
var isNone = Ember.isNone;
var forEach = Ember.EnumerableUtils.forEach;
var indexOf = Ember.EnumerableUtils.indexOf;
var map = Ember.EnumerableUtils.map;
var Promise = Ember.RSVP.Promise;
var copy = Ember.copy;
var Store, PromiseObject, PromiseArray;
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +reference+ means a record reference object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a subclass of DS.Model.
// Used by the store to normalize IDs entering the store. Despite the fact
// that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
function coerceId(id) {
return id == null ? null : id+'';
}
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `DS.Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```javascript
MyApp.Store = DS.Store.extend();
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Store`'s `find()` method:
```javascript
var person = store.find('person', 123);
```
If your application has multiple `DS.Store` instances (an unusual case), you can
specify which store should be used:
```javascript
var person = store.find(App.Person, 123);
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```javascript
MyApp.store = DS.Store.create({
adapter: 'MyApp.CustomAdapter'
});
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
@class Store
@namespace DS
@extends Ember.Object
*/
Store = Ember.Object.extend({
/**
@method init
@private
*/
init: function() {
// internal bookkeeping; not observable
this.typeMaps = {};
this.recordArrayManager = DS.RecordArrayManager.create({
store: this
});
this._relationshipChanges = {};
this._pendingSave = [];
},
/**
The adapter to use to communicate to a backend server or other persistence layer.
This can be specified as an instance, class, or string.
If you want to specify `App.CustomAdapter` as a string, do:
```js
adapter: 'custom'
```
@property adapter
@default DS.RESTAdapter
@type {DS.Adapter|String}
*/
adapter: '-rest',
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize: function(record, options) {
return this.serializerFor(record.constructor.typeKey).serialize(record, options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@returns DS.Adapter
*/
defaultAdapter: Ember.computed('adapter', function() {
var adapter = get(this, 'adapter');
Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof DS.Adapter));
if (typeof adapter === 'string') {
adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest');
}
if (DS.Adapter.detect(adapter)) {
adapter = adapter.create({
container: this.container
});
}
return adapter;
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of `App.Post`:
```js
store.createRecord('post', {
title: "Rails is omakase"
});
```
@method createRecord
@param {String} type
@param {Object} properties a hash of properties to set on the
newly created record.
@returns {DS.Model} record
*/
createRecord: function(type, properties) {
type = this.modelFor(type);
properties = copy(properties) || {};
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (isNone(properties.id)) {
properties.id = this._generateId(type);
}
// Coerce ID to a string
properties.id = coerceId(properties.id);
var record = this.buildRecord(type, properties.id);
// Move the record out of its initial `empty` state into
// the `loaded` state.
record.loadedData();
// Set the properties specified on the record.
record.setProperties(properties);
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method _generateId
@private
@param {String} type
@returns {String} if the adapter can generate one, an ID
*/
_generateId: function(type) {
var adapter = this.adapterFor(type);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
var post = store.createRecord('post', {
title: "Rails is omakase"
});
store.deleteRecord(post);
```
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord: function(record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store. Only
non-dirty records can be unloaded.
Example
```javascript
store.find('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord: function(record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
This is the main entry point into finding records. The first parameter to
this method is the model's name as a string.
---
To find a record by ID, pass the `id` as the second parameter:
```javascript
store.find('person', 1);
```
The `find` method will always return a **promise** that will be resolved
with the record. If the record was already in the store, the promise will
be resolved immediately. Otherwise, the store will ask the adapter's `find`
method to find the necessary data.
The `find` method will always resolve its promise with the same object for
a given type and `id`.
---
To find all records for a type, call `find` with no additional parameters:
```javascript
store.find('person');
```
This will ask the adapter's `findAll` method to find the records for the
given type, and return a promise that will be resolved once the server
returns the values.
---
To find a record by a query, call `find` with a hash as the second
parameter:
```javascript
store.find(App.Person, { page: 1 });
```
This will ask the adapter's `findQuery` method to find the records for
the query, and return a promise that will be resolved once the server
responds.
@method find
@param {String or subclass of DS.Model} type
@param {Object|String|Integer|null} id
@return {Promise} promise
*/
find: function(type, id) {
Ember.assert("You need to pass a type to the store's find method", arguments.length >= 1);
Ember.assert("You may not pass `" + id + "` as id to the store's find method", arguments.length === 1 || !Ember.isNone(id));
if (arguments.length === 1) {
return this.findAll(type);
}
// We are passed a query instead of an id.
if (Ember.typeOf(id) === 'object') {
return this.findQuery(type, id);
}
return this.findById(type, coerceId(id));
},
/**
This method returns a record for a given type and id combination.
@method findById
@private
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {Promise} promise
*/
findById: function(type, id) {
type = this.modelFor(type);
var record = this.recordForId(type, id);
var fetchedRecord = this.fetchRecord(record);
return promiseObject(fetchedRecord || record, "DS: Store#findById " + type + " with id: " + id);
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} type
@param {Array} ids
@returns {Promise} promise
*/
findByIds: function(type, ids) {
var store = this;
var promiseLabel = "DS: Store#findByIds " + type;
return promiseArray(Ember.RSVP.all(map(ids, function(id) {
return store.findById(type, id);
})).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete"));
},
/**
This method is called by `findById` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method fetchRecord
@private
@param {DS.Model} record
@returns {Promise} promise
*/
fetchRecord: function(record) {
if (isNone(record)) { return null; }
if (record._loadingPromise) { return record._loadingPromise; }
if (!get(record, 'isEmpty')) { return null; }
var type = record.constructor,
id = get(record, 'id');
var adapter = this.adapterFor(type);
Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", adapter.find);
var promise = _find(adapter, this, type, id);
record.loadingData(promise);
return promise;
},
/**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it's available.
Otherwise, it will return null.
```js
var post = store.getById('post', 1);
```
@method getById
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@param {DS.Model} record
*/
getById: function(type, id) {
if (this.hasRecordForId(type, id)) {
return this.recordForId(type, id);
} else {
return null;
}
},
/**
This method is called by the record's `reload` method.
This method calls the adapter's `find` method, which returns a promise. When
**that** promise resolves, `reloadRecord` will resolve the promise returned
by the record's `reload`.
@method reloadRecord
@private
@param {DS.Model} record
@return {Promise} promise
*/
reloadRecord: function(record) {
var type = record.constructor,
adapter = this.adapterFor(type),
id = get(record, 'id');
Ember.assert("You cannot reload a record without an ID", id);
Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to reload a record but your adapter does not implement `find`", adapter.find);
return _find(adapter, this, type, id);
},
/**
This method takes a list of records, groups the records by type,
converts the records into IDs, and then invokes the adapter's `findMany`
method.
The records are grouped by type to invoke `findMany` on adapters
for each unique type in records.
It is used both by a brand new relationship (via the `findMany`
method) or when the data underlying an existing relationship
changes.
@method fetchMany
@private
@param {Array} records
@param {DS.Model} owner
@return {Promise} promise
*/
fetchMany: function(records, owner) {
if (!records.length) { return; }
// Group By Type
var recordsByTypeMap = Ember.MapWithDefault.create({
defaultValue: function() { return Ember.A(); }
});
forEach(records, function(record) {
recordsByTypeMap.get(record.constructor).push(record);
});
var promises = [];
forEach(recordsByTypeMap, function(type, records) {
var ids = records.mapProperty('id'),
adapter = this.adapterFor(type);
Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load many records but your adapter does not implement `findMany`", adapter.findMany);
promises.push(_findMany(adapter, this, type, ids, owner));
}, this);
return Ember.RSVP.all(promises);
},
/**
Returns true if a record for a given type and ID is already loaded.
@method hasRecordForId
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@returns {Boolean}
*/
hasRecordForId: function(type, id) {
id = coerceId(id);
type = this.modelFor(type);
return !!this.typeMapFor(type).idToRecord[id];
},
/**
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the `empty` state.
@method recordForId
@private
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@returns {DS.Model} record
*/
recordForId: function(type, id) {
type = this.modelFor(type);
id = coerceId(id);
var record = this.typeMapFor(type).idToRecord[id];
if (!record) {
record = this.buildRecord(type, id);
}
return record;
},
/**
@method findMany
@private
@param {DS.Model} owner
@param {Array} records
@param {String or subclass of DS.Model} type
@param {Resolver} resolver
@return {DS.ManyArray} records
*/
findMany: function(owner, records, type, resolver) {
type = this.modelFor(type);
records = Ember.A(records);
var unloadedRecords = records.filterProperty('isEmpty', true),
manyArray = this.recordArrayManager.createManyArray(type, records);
forEach(unloadedRecords, function(record) {
record.loadingData();
});
manyArray.loadingRecordsCount = unloadedRecords.length;
if (unloadedRecords.length) {
forEach(unloadedRecords, function(record) {
this.recordArrayManager.registerWaitingRecordArray(record, manyArray);
}, this);
resolver.resolve(this.fetchMany(unloadedRecords, owner));
} else {
if (resolver) { resolver.resolve(); }
manyArray.set('isLoaded', true);
once(manyArray, 'trigger', 'didLoad');
}
return manyArray;
},
/**
If a relationship was originally populated by the adapter as a link
(as opposed to a list of IDs), this method is called when the
relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the
adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and
then use that URL in the future to make a request for the relationship.
@method findHasMany
@private
@param {DS.Model} owner
@param {any} link
@param {String or subclass of DS.Model} type
@return {Promise} promise
*/
findHasMany: function(owner, link, relationship, resolver) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", adapter.findHasMany);
var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([]));
resolver.resolve(_findHasMany(adapter, this, owner, link, relationship));
return records;
},
/**
@method findBelongsTo
@private
@param {DS.Model} owner
@param {any} link
@param {Relationship} relationship
@return {Promise} promise
*/
findBelongsTo: function(owner, link, relationship) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", adapter.findBelongsTo);
return _findBelongsTo(adapter, this, owner, link, relationship);
},
/**
This method delegates a query to the adapter. This is the one place where
adapter-level semantics are exposed to the application.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
This method returns a promise, which is resolved with a `RecordArray`
once the server returns.
@method findQuery
@private
@param {String or subclass of DS.Model} type
@param {any} query an opaque query to be used by the adapter
@return {Promise} promise
*/
findQuery: function(type, query) {
type = this.modelFor(type);
var array = this.recordArrayManager
.createAdapterPopulatedRecordArray(type, query);
var adapter = this.adapterFor(type);
Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery);
return promiseArray(_findQuery(adapter, this, type, query, array));
},
/**
This method returns an array of all records adapter can find.
It triggers the adapter's `findAll` method to give it an opportunity to populate
the array with records of that type.
@method findAll
@private
@param {String or subclass of DS.Model} type
@return {DS.AdapterPopulatedRecordArray}
*/
findAll: function(type) {
type = this.modelFor(type);
return this.fetchAll(type, this.all(type));
},
/**
@method fetchAll
@private
@param {DS.Model} type
@param {DS.RecordArray} array
@returns {Promise} promise
*/
fetchAll: function(type, array) {
var adapter = this.adapterFor(type),
sinceToken = this.typeMapFor(type).metadata.since;
set(array, 'isUpdating', true);
Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll);
return promiseArray(_findAll(adapter, this, type, sinceToken));
},
/**
@method didUpdateAll
@param {DS.Model} type
*/
didUpdateAll: function(type) {
var findAllCache = this.typeMapFor(type).findAllCache;
set(findAllCache, 'isUpdating', false);
},
/**
This method returns a filtered array that contains all of the known records
for a given type.
Note that because it's just a filter, it will have any locally
created records of the type.
Also note that multiple calls to `all` for a given type will always
return the same RecordArray.
Example
```javascript
var local_posts = store.all(App.Post);
```
@method all
@param {String or subclass of DS.Model} type
@return {DS.RecordArray}
*/
all: function(type) {
type = this.modelFor(type);
var typeMap = this.typeMapFor(type),
findAllCache = typeMap.findAllCache;
if (findAllCache) { return findAllCache; }
var array = this.recordArrayManager.createRecordArray(type);
typeMap.findAllCache = array;
return array;
},
/**
This method unloads all of the known records for a given type.
```javascript
store.unloadAll(App.Post);
```
@method unloadAll
@param {String or subclass of DS.Model} type
*/
unloadAll: function(type) {
var modelType = this.modelFor(type);
var typeMap = this.typeMapFor(modelType);
var records = typeMap.records.slice();
var record;
for (var i = 0; i < records.length; i++) {
record = records[i];
record.unloadRecord();
record.destroy(); // maybe within unloadRecord
}
typeMap.findAllCache = null;
},
/**
Takes a type and filter function, and returns a live RecordArray that
remains up to date as new records are loaded into the store or created
locally.
The callback function takes a materialized record, and returns true
if the record should be included in the filter and false if it should
not.
The filter function is called once on all records for the type when
it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the
filter function will be invoked again to determine whether it should
still be in the array.
Optionally you can pass a query which will be triggered at first. The
results returned by the server could then appear in the filter if they
match the filter function.
Example
```javascript
store.filter(App.Post, {unread: true}, function(post) {
return post.get('unread');
}).then(function(unreadPosts) {
unreadPosts.get('length'); // 5
var unreadPost = unreadPosts.objectAt(0);
unreadPost.set('unread', false);
unreadPosts.get('length'); // 4
});
```
@method filter
@param {String or subclass of DS.Model} type
@param {Object} query optional query
@param {Function} filter
@return {DS.PromiseArray}
*/
filter: function(type, query, filter) {
var promise;
// allow an optional server query
if (arguments.length === 3) {
promise = this.findQuery(type, query);
} else if (arguments.length === 2) {
filter = query;
}
type = this.modelFor(type);
var array = this.recordArrayManager
.createFilteredRecordArray(type, filter);
promise = promise || Promise.cast(array);
return promiseArray(promise.then(function() {
return array;
}, null, "DS: Store#filter of " + type));
},
/**
This method returns if a certain record is already loaded
in the store. Use this function to know beforehand if a find()
will result in a request or that it will be a cache hit.
Example
```javascript
store.recordIsLoaded(App.Post, 1); // false
store.find(App.Post, 1).then(function() {
store.recordIsLoaded(App.Post, 1); // true
});
```
@method recordIsLoaded
@param {String or subclass of DS.Model} type
@param {string} id
@return {boolean}
*/
recordIsLoaded: function(type, id) {
if (!this.hasRecordForId(type, id)) { return false; }
return !get(this.recordForId(type, id), 'isEmpty');
},
/**
This method returns the metadata for a specific type.
@method metadataFor
@param {String or subclass of DS.Model} type
@return {object}
*/
metadataFor: function(type) {
type = this.modelFor(type);
return this.typeMapFor(type).metadata;
},
// ............
// . UPDATING .
// ............
/**
If the adapter updates attributes or acknowledges creation
or deletion, the record will notify the store to update its
membership in any filters.
To avoid thrashing, this method is invoked only once per
run loop per record.
@method dataWasUpdated
@private
@param {Class} type
@param {DS.Model} record
*/
dataWasUpdated: function(type, record) {
this.recordArrayManager.recordDidChange(record);
},
// ..............
// . PERSISTING .
// ..............
/**
This method is called by `record.save`, and gets passed a
resolver for the promise that `record.save` returns.
It schedules saving to happen at the end of the run loop.
@method scheduleSave
@private
@param {DS.Model} record
@param {Resolver} resolver
*/
scheduleSave: function(record, resolver) {
record.adapterWillCommit();
this._pendingSave.push([record, resolver]);
once(this, 'flushPendingSave');
},
/**
This method is called at the end of the run loop, and
flushes any records passed into `scheduleSave`
@method flushPendingSave
@private
*/
flushPendingSave: function() {
var pending = this._pendingSave.slice();
this._pendingSave = [];
forEach(pending, function(tuple) {
var record = tuple[0], resolver = tuple[1],
adapter = this.adapterFor(record.constructor),
operation;
if (get(record, 'isNew')) {
operation = 'createRecord';
} else if (get(record, 'isDeleted')) {
operation = 'deleteRecord';
} else {
operation = 'updateRecord';
}
resolver.resolve(_commit(adapter, this, operation, record));
}, this);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is resolved.
If the data provides a server-generated ID, it will
update the record and the store's indexes.
@method didSaveRecord
@private
@param {DS.Model} record the in-flight record
@param {Object} data optional data (see above)
*/
didSaveRecord: function(record, data) {
if (data) {
// normalize relationship IDs into records
data = normalizeRelationships(this, record.constructor, data, record);
this.updateId(record, data);
}
record.adapterDidCommit(data);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected with a `DS.InvalidError`.
@method recordWasInvalid
@private
@param {DS.Model} record
@param {Object} errors
*/
recordWasInvalid: function(record, errors) {
record.adapterDidInvalidate(errors);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected (with anything other than a `DS.InvalidError`).
@method recordWasError
@private
@param {DS.Model} record
*/
recordWasError: function(record) {
record.adapterDidError();
},
/**
When an adapter's `createRecord`, `updateRecord` or `deleteRecord`
resolves with data, this method extracts the ID from the supplied
data.
@method updateId
@private
@param {DS.Model} record
@param {Object} data
*/
updateId: function(record, data) {
var oldId = get(record, 'id'),
id = coerceId(data.id);
Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId);
this.typeMapFor(record.constructor).idToRecord[id] = record;
set(record, 'id', id);
},
/**
Returns a map of IDs to client IDs for a given type.
@method typeMapFor
@private
@param type
@return {Object} typeMap
*/
typeMapFor: function(type) {
var typeMaps = get(this, 'typeMaps'),
guid = Ember.guidFor(type),
typeMap;
typeMap = typeMaps[guid];
if (typeMap) { return typeMap; }
typeMap = {
idToRecord: {},
records: [],
metadata: {},
type: type
};
typeMaps[guid] = typeMap;
return typeMap;
},
// ................
// . LOADING DATA .
// ................
/**
This internal method is used by `push`.
@method _load
@private
@param {String or subclass of DS.Model} type
@param {Object} data
@param {Boolean} partial the data should be merged into
the existing data, not replace it.
*/
_load: function(type, data, partial) {
var id = coerceId(data.id),
record = this.recordForId(type, id);
record.setupData(data, partial);
this.recordArrayManager.recordDidChange(record);
return record;
},
/**
Returns a model class for a particular key. Used by
methods that take a type key (like `find`, `createRecord`,
etc.)
@method modelFor
@param {String or subclass of DS.Model} key
@returns {subclass of DS.Model}
*/
modelFor: function(key) {
var factory;
if (typeof key === 'string') {
var normalizedKey = this.container.normalize('model:' + key);
factory = this.container.lookupFactory(normalizedKey);
if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); }
factory.typeKey = normalizedKey.split(':', 2)[1];
} else {
// A factory already supplied.
factory = key;
}
factory.store = this;
return factory;
},
/**
Push some data for a given type into the store.
This method expects normalized data:
* The ID is a key named `id` (an ID is mandatory)
* The names of attributes are the ones you used in
your model's `DS.attr`s.
* Your relationships must be:
* represented as IDs or Arrays of IDs
* represented as model instances
* represented as URLs, under the `links` key
For this model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
children: DS.hasMany('person')
});
```
To represent the children as IDs:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
children: [1, 2, 3]
}
```
To represent the children relationship as a URL:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
links: {
children: "/people/1/children"
}
}
```
If you're streaming data or implementing an adapter,
make sure that you have converted the incoming data
into this form.
This method can be used both to push in brand new
records, as well as to update existing records.
@method push
@param {String or subclass of DS.Model} type
@param {Object} data
@returns {DS.Model} the record that was created or
updated.
*/
push: function(type, data, _partial) {
// _partial is an internal param used by `update`.
// If passed, it means that the data should be
// merged into the existing data, not replace it.
Ember.assert("You must include an `id` in a hash passed to `push`", data.id != null);
type = this.modelFor(type);
// normalize relationship IDs into records
data = normalizeRelationships(this, type, data);
this._load(type, data, _partial);
return this.recordForId(type, data.id);
},
/**
Push some raw data into the store.
The data will be automatically deserialized using the
serializer for the `type` param.
This method can be used both to push in brand new
records, as well as to update existing records.
You can push in more than one type of object at once.
All objects should be in the format expected by the
serializer.
```js
App.ApplicationSerializer = DS.ActiveModelSerializer;
var pushData = {
posts: [
{id: 1, post_title: "Great post", comment_ids: [2]}
],
comments: [
{id: 2, comment_body: "Insightful comment"}
]
}
store.pushPayload('post', pushData);
```
@method pushPayload
@param {String} type
@param {Object} payload
*/
pushPayload: function (type, payload) {
var serializer;
if (!payload) {
payload = type;
serializer = defaultSerializer(this.container);
Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", serializer.pushPayload);
} else {
serializer = this.serializerFor(type);
}
serializer.pushPayload(this, payload);
},
update: function(type, data) {
Ember.assert("You must include an `id` in a hash passed to `update`", data.id != null);
return this.push(type, data, true);
},
/**
If you have an Array of normalized data to push,
you can call `pushMany` with the Array, and it will
call `push` repeatedly for you.
@method pushMany
@param {String or subclass of DS.Model} type
@param {Array} datas
@return {Array}
*/
pushMany: function(type, datas) {
return map(datas, function(data) {
return this.push(type, data);
}, this);
},
/**
If you have some metadata to set for a type
you can call `metaForType`.
@method metaForType
@param {String or subclass of DS.Model} type
@param {Object} metadata
*/
metaForType: function(type, metadata) {
type = this.modelFor(type);
Ember.merge(this.typeMapFor(type).metadata, metadata);
},
/**
Build a brand new record for a given type, ID, and
initial data.
@method buildRecord
@private
@param {subclass of DS.Model} type
@param {String} id
@param {Object} data
@returns {DS.Model} record
*/
buildRecord: function(type, id, data) {
var typeMap = this.typeMapFor(type),
idToRecord = typeMap.idToRecord;
Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]);
Ember.assert("`" + Ember.inspect(type)+ "` does not appear to be an ember-data model", (typeof type._create === 'function') );
// lookupFactory should really return an object that creates
// instances with the injections applied
var record = type._create({
id: id,
store: this,
container: this.container
});
if (data) {
record.setupData(data);
}
// if we're creating an item, this process will be done
// later, once the object has been persisted.
if (id) {
idToRecord[id] = record;
}
typeMap.records.push(record);
return record;
},
// ...............
// . DESTRUCTION .
// ...............
/**
When a record is destroyed, this un-indexes it and
removes it from any record arrays so it can be GCed.
@method dematerializeRecord
@private
@param {DS.Model} record
*/
dematerializeRecord: function(record) {
var type = record.constructor,
typeMap = this.typeMapFor(type),
id = get(record, 'id');
record.updateRecordArrays();
if (id) {
delete typeMap.idToRecord[id];
}
var loc = indexOf(typeMap.records, record);
typeMap.records.splice(loc, 1);
},
// ........................
// . RELATIONSHIP CHANGES .
// ........................
addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) {
var clientId = childRecord.clientId,
parentClientId = parentRecord ? parentRecord : parentRecord;
var key = childKey + parentKey;
var changes = this._relationshipChanges;
if (!(clientId in changes)) {
changes[clientId] = {};
}
if (!(parentClientId in changes[clientId])) {
changes[clientId][parentClientId] = {};
}
if (!(key in changes[clientId][parentClientId])) {
changes[clientId][parentClientId][key] = {};
}
changes[clientId][parentClientId][key][change.changeType] = change;
},
removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) {
var clientId = clientRecord.clientId,
parentClientId = parentRecord ? parentRecord.clientId : parentRecord;
var changes = this._relationshipChanges;
var key = childKey + parentKey;
if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){
return;
}
delete changes[clientId][parentClientId][key][type];
},
relationshipChangePairsFor: function(record){
var toReturn = [];
if( !record ) { return toReturn; }
//TODO(Igor) What about the other side
var changesObject = this._relationshipChanges[record.clientId];
for (var objKey in changesObject){
if(changesObject.hasOwnProperty(objKey)){
for (var changeKey in changesObject[objKey]){
if(changesObject[objKey].hasOwnProperty(changeKey)){
toReturn.push(changesObject[objKey][changeKey]);
}
}
}
}
return toReturn;
},
// ......................
// . PER-TYPE ADAPTERS
// ......................
/**
Returns the adapter for a given type.
@method adapterFor
@private
@param {subclass of DS.Model} type
@returns DS.Adapter
*/
adapterFor: function(type) {
var container = this.container, adapter;
if (container) {
adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application');
}
return adapter || get(this, 'defaultAdapter');
},
// ..............................
// . RECORD CHANGE NOTIFICATION .
// ..............................
/**
Returns an instance of the serializer for a given type. For
example, `serializerFor('person')` will return an instance of
`App.PersonSerializer`.
If no `App.PersonSerializer` is found, this method will look
for an `App.ApplicationSerializer` (the default serializer for
your entire application).
If no `App.ApplicationSerializer` is found, it will fall back
to an instance of `DS.JSONSerializer`.
@method serializerFor
@private
@param {String} type the record to serialize
@return {DS.Serializer}
*/
serializerFor: function(type) {
type = this.modelFor(type);
var adapter = this.adapterFor(type);
return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer);
},
willDestroy: function() {
var map = this.typeMaps;
var keys = Ember.keys(map);
var store = this;
var types = keys.map(byType);
this.recordArrayManager.destroy();
types.forEach(this.unloadAll, this);
function byType(entry) {
return map[entry].type;
}
}
});
function normalizeRelationships(store, type, data, record) {
type.eachRelationship(function(key, relationship) {
// A link (usually a URL) was already provided in
// normalized form
if (data.links && data.links[key]) {
if (record && relationship.options.async) { record._relationships[key] = null; }
return;
}
var kind = relationship.kind,
value = data[key];
if (value == null) { return; }
if (kind === 'belongsTo') {
deserializeRecordId(store, data, key, relationship, value);
} else if (kind === 'hasMany') {
deserializeRecordIds(store, data, key, relationship, value);
addUnsavedRecords(record, key, value);
}
});
return data;
}
function deserializeRecordId(store, data, key, relationship, id) {
if (isNone(id) || id instanceof DS.Model) {
return;
}
var type;
if (typeof id === 'number' || typeof id === 'string') {
type = typeFor(relationship, key, data);
data[key] = store.recordForId(type, id);
} else if (typeof id === 'object') {
// polymorphic
data[key] = store.recordForId(id.type, id.id);
}
}
function typeFor(relationship, key, data) {
if (relationship.options.polymorphic) {
return data[key + "Type"];
} else {
return relationship.type;
}
}
function deserializeRecordIds(store, data, key, relationship, ids) {
for (var i=0, l=ids.length; i<l; i++) {
deserializeRecordId(store, ids, i, relationship, ids[i]);
}
}
// If there are any unsaved records that are in a hasMany they won't be
// in the payload, so add them back in manually.
function addUnsavedRecords(record, key, data) {
if(record) {
data.pushObjects(record.get(key).filterBy('isNew'));
}
}
// Delegation to the adapter and promise management
/**
A `PromiseArray` is an object that acts like both an `Ember.Array`
and a promise. When the promise is resolved the the resulting value
will be set to the `PromiseArray`'s `content` property. This makes
it easy to create data bindings with the `PromiseArray` that will be
updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseArray = DS.PromiseArray.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseArray.get('length'); // 0
promiseArray.then(function() {
promiseArray.get('length'); // 100
});
```
@class PromiseArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.PromiseProxyMixin
*/
PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);
/**
A `PromiseObject` is an object that acts like both an `Ember.Object`
and a promise. When the promise is resolved the the resulting value
will be set to the `PromiseObject`'s `content` property. This makes
it easy to create data bindings with the `PromiseObject` that will
be updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseObject = DS.PromiseObject.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseObject.get('name'); // null
promiseObject.then(function() {
promiseObject.get('name'); // 'Tomster'
});
```
@class PromiseObject
@namespace DS
@extends Ember.ObjectProxy
@uses Ember.PromiseProxyMixin
*/
PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);
function promiseObject(promise, label) {
return PromiseObject.create({
promise: Promise.cast(promise, label)
});
}
function promiseArray(promise, label) {
return PromiseArray.create({
promise: Promise.cast(promise, label)
});
}
function isThenable(object) {
return object && typeof object.then === 'function';
}
function serializerFor(container, type, defaultSerializer) {
return container.lookup('serializer:'+type) ||
container.lookup('serializer:application') ||
container.lookup('serializer:' + defaultSerializer) ||
container.lookup('serializer:-default');
}
function defaultSerializer(container) {
return container.lookup('serializer:application') ||
container.lookup('serializer:-default');
}
function serializerForAdapter(adapter, type) {
var serializer = adapter.serializer,
defaultSerializer = adapter.defaultSerializer,
container = adapter.container;
if (container && serializer === undefined) {
serializer = serializerFor(container, type.typeKey, defaultSerializer);
}
if (serializer === null || serializer === undefined) {
serializer = {
extract: function(store, type, payload) { return payload; }
};
}
return serializer;
}
function _find(adapter, store, type, id) {
var promise = adapter.find(store, type, id),
serializer = serializerForAdapter(adapter, type),
label = "DS: Handle Adapter#find of " + type + " with id: " + id;
return Promise.cast(promise, label).then(function(adapterPayload) {
Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", adapterPayload);
var payload = serializer.extract(store, type, adapterPayload, id, 'find');
return store.push(type, payload);
}, function(error) {
var record = store.getById(type, id);
record.notFound();
throw error;
}, "DS: Extract payload of '" + type + "'");
}
function _findMany(adapter, store, type, ids, owner) {
var promise = adapter.findMany(store, type, ids, owner),
serializer = serializerForAdapter(adapter, type),
label = "DS: Handle Adapter#findMany of " + type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findMany');
Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
store.pushMany(type, payload);
}, null, "DS: Extract payload of " + type);
}
function _findHasMany(adapter, store, record, link, relationship) {
var promise = adapter.findHasMany(store, record, link, relationship),
serializer = serializerForAdapter(adapter, relationship.type),
label = "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findHasMany');
Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
var records = store.pushMany(relationship.type, payload);
record.updateHasMany(relationship.key, records);
}, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type);
}
function _findBelongsTo(adapter, store, record, link, relationship) {
var promise = adapter.findBelongsTo(store, record, link, relationship),
serializer = serializerForAdapter(adapter, relationship.type),
label = "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findBelongsTo');
var record = store.push(relationship.type, payload);
record.updateBelongsTo(relationship.key, record);
return record;
}, null, "DS: Extract payload of " + record + " : " + relationship.type);
}
function _findAll(adapter, store, type, sinceToken) {
var promise = adapter.findAll(store, type, sinceToken),
serializer = serializerForAdapter(adapter, type),
label = "DS: Handle Adapter#findAll of " + type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findAll');
Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
store.pushMany(type, payload);
store.didUpdateAll(type);
return store.all(type);
}, null, "DS: Extract payload of findAll " + type);
}
function _findQuery(adapter, store, type, query, recordArray) {
var promise = adapter.findQuery(store, type, query, recordArray),
serializer = serializerForAdapter(adapter, type),
label = "DS: Handle Adapter#findQuery of " + type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findQuery');
Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
recordArray.load(payload);
return recordArray;
}, null, "DS: Extract payload of findQuery " + type);
}
function _commit(adapter, store, operation, record) {
var type = record.constructor,
promise = adapter[operation](store, type, record),
serializer = serializerForAdapter(adapter, type),
label = "DS: Extract and notify about " + operation + " completion of " + record;
Ember.assert("Your adapter's '" + operation + "' method must return a promise, but it returned " + promise, isThenable(promise));
return promise.then(function(adapterPayload) {
var payload;
if (adapterPayload) {
payload = serializer.extract(store, type, adapterPayload, get(record, 'id'), operation);
} else {
payload = adapterPayload;
}
store.didSaveRecord(record, payload);
return record;
}, function(reason) {
if (reason instanceof DS.InvalidError) {
store.recordWasInvalid(record, reason.errors);
} else {
store.recordWasError(record, reason);
}
throw reason;
}, label);
}
__exports__.Store = Store;
__exports__.PromiseArray = PromiseArray;
__exports__.PromiseObject = PromiseObject;
__exports__["default"] = Store;
});
define("ember-data/lib/transforms",
["./transforms/base","./transforms/number","./transforms/date","./transforms/string","./transforms/boolean","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var NumberTransform = __dependency2__["default"];
var DateTransform = __dependency3__["default"];
var StringTransform = __dependency4__["default"];
var BooleanTransform = __dependency5__["default"];
__exports__.Transform = Transform;
__exports__.NumberTransform = NumberTransform;
__exports__.DateTransform = DateTransform;
__exports__.StringTransform = StringTransform;
__exports__.BooleanTransform = BooleanTransform;
});
define("ember-data/lib/transforms/base",
["exports"],
function(__exports__) {
"use strict";
/**
The `DS.Transform` class is used to serialize and deserialize model
attributes when they are saved or loaded from an
adapter. Subclassing `DS.Transform` is useful for creating custom
attributes. All subclasses of `DS.Transform` must implement a
`serialize` and a `deserialize` method.
Example
```javascript
App.RawTransform = DS.Transform.extend({
deserialize: function(serialized) {
return serialized;
},
serialize: function(deserialized) {
return deserialized;
}
});
```
Usage
```javascript
var attr = DS.attr;
App.Requirement = DS.Model.extend({
name: attr('string'),
optionsArray: attr('raw')
});
```
@class Transform
@namespace DS
*/
var Transform = Ember.Object.extend({
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
serialize: function(deserialized) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param deserialized The deserialized value
@return The serialized value
*/
serialize: Ember.required(),
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialize
@param serialized The serialized value
@return The deserialized value
*/
deserialize: Ember.required()
});
__exports__["default"] = Transform;
});
define("ember-data/lib/transforms/boolean",
["./base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
/**
The `DS.BooleanTransform` class is used to serialize and deserialize
boolean attributes on Ember Data record objects. This transform is
used when `boolean` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
isAdmin: attr('boolean'),
name: attr('string'),
email: attr('string')
});
```
@class BooleanTransform
@extends DS.Transform
@namespace DS
*/
var BooleanTransform = Transform.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "boolean") {
return serialized;
} else if (type === "string") {
return serialized.match(/^true$|^t$|^1$/i) !== null;
} else if (type === "number") {
return serialized === 1;
} else {
return false;
}
},
serialize: function(deserialized) {
return Boolean(deserialized);
}
});
__exports__["default"] = BooleanTransform;
});
define("ember-data/lib/transforms/date",
["./base","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
The `DS.DateTransform` class is used to serialize and deserialize
date attributes on Ember Data record objects. This transform is used
when `date` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
```javascript
var attr = DS.attr;
App.Score = DS.Model.extend({
value: attr('number'),
player: DS.belongsTo('player'),
date: attr('date')
});
```
@class DateTransform
@extends DS.Transform
@namespace DS
*/
var Transform = __dependency1__["default"];
var DateTransform = Transform.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "string") {
return new Date(Ember.Date.parse(serialized));
} else if (type === "number") {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is not present in the data,
// return undefined, not null.
return serialized;
} else {
return null;
}
},
serialize: function(date) {
if (date instanceof Date) {
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var pad = function(num) {
return num < 10 ? "0"+num : ""+num;
};
var utcYear = date.getUTCFullYear(),
utcMonth = date.getUTCMonth(),
utcDayOfMonth = date.getUTCDate(),
utcDay = date.getUTCDay(),
utcHours = date.getUTCHours(),
utcMinutes = date.getUTCMinutes(),
utcSeconds = date.getUTCSeconds();
var dayOfWeek = days[utcDay];
var dayOfMonth = pad(utcDayOfMonth);
var month = months[utcMonth];
return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " +
pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT";
} else {
return null;
}
}
});
__exports__["default"] = DateTransform;
});
define("ember-data/lib/transforms/number",
["./base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var empty = Ember.isEmpty;
/**
The `DS.NumberTransform` class is used to serialize and deserialize
numeric attributes on Ember Data record objects. This transform is
used when `number` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.Score = DS.Model.extend({
value: attr('number'),
player: DS.belongsTo('player'),
date: attr('date')
});
```
@class NumberTransform
@extends DS.Transform
@namespace DS
*/
var NumberTransform = Transform.extend({
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
},
serialize: function(deserialized) {
return empty(deserialized) ? null : Number(deserialized);
}
});
__exports__["default"] = NumberTransform;
});
define("ember-data/lib/transforms/string",
["./base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var none = Ember.isNone;
/**
The `DS.StringTransform` class is used to serialize and deserialize
string attributes on Ember Data record objects. This transform is
used when `string` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
isAdmin: attr('boolean'),
name: attr('string'),
email: attr('string')
});
```
@class StringTransform
@extends DS.Transform
@namespace DS
*/
var StringTransform = Transform.extend({
deserialize: function(serialized) {
return none(serialized) ? null : String(serialized);
},
serialize: function(deserialized) {
return none(deserialized) ? null : String(deserialized);
}
});
__exports__["default"] = StringTransform;
});
define("ember-inflector/lib/ext/string",
["../system/string"],
function(__dependency1__) {
"use strict";
var pluralize = __dependency1__.pluralize;
var singularize = __dependency1__.singularize;
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}}
@method pluralize
@for String
*/
String.prototype.pluralize = function() {
return pluralize(this);
};
/**
See {{#crossLink "Ember.String/singularize"}}{{/crossLink}}
@method singularize
@for String
*/
String.prototype.singularize = function() {
return singularize(this);
};
}
});
define("ember-inflector/lib/main",
["./system","./ext/string","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var Inflector = __dependency1__.Inflector;
var inflections = __dependency1__.inflections;
var pluralize = __dependency1__.pluralize;
var singularize = __dependency1__.singularize;
Inflector.defaultRules = inflections;
Ember.Inflector = Inflector;
Ember.String.pluralize = pluralize;
Ember.String.singularize = singularize;
__exports__["default"] = Inflector;
__exports__.pluralize = pluralize;
__exports__.singularize = singularize;
});
define("ember-inflector/lib/system",
["./system/inflector","./system/string","./system/inflections","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var Inflector = __dependency1__["default"];
var pluralize = __dependency2__.pluralize;
var singularize = __dependency2__.singularize;
var defaultRules = __dependency3__["default"];
Inflector.inflector = new Inflector(defaultRules);
__exports__.Inflector = Inflector;
__exports__.singularize = singularize;
__exports__.pluralize = pluralize;
__exports__.defaultRules = defaultRules;
});
define("ember-inflector/lib/system/inflections",
["exports"],
function(__exports__) {
"use strict";
var defaultRules = {
plurals: [
[/$/, 's'],
[/s$/i, 's'],
[/^(ax|test)is$/i, '$1es'],
[/(octop|vir)us$/i, '$1i'],
[/(octop|vir)i$/i, '$1i'],
[/(alias|status)$/i, '$1es'],
[/(bu)s$/i, '$1ses'],
[/(buffal|tomat)o$/i, '$1oes'],
[/([ti])um$/i, '$1a'],
[/([ti])a$/i, '$1a'],
[/sis$/i, 'ses'],
[/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],
[/(hive)$/i, '$1s'],
[/([^aeiouy]|qu)y$/i, '$1ies'],
[/(x|ch|ss|sh)$/i, '$1es'],
[/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'],
[/^(m|l)ouse$/i, '$1ice'],
[/^(m|l)ice$/i, '$1ice'],
[/^(ox)$/i, '$1en'],
[/^(oxen)$/i, '$1'],
[/(quiz)$/i, '$1zes']
],
singular: [
[/s$/i, ''],
[/(ss)$/i, '$1'],
[/(n)ews$/i, '$1ews'],
[/([ti])a$/i, '$1um'],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'],
[/(^analy)(sis|ses)$/i, '$1sis'],
[/([^f])ves$/i, '$1fe'],
[/(hive)s$/i, '$1'],
[/(tive)s$/i, '$1'],
[/([lr])ves$/i, '$1f'],
[/([^aeiouy]|qu)ies$/i, '$1y'],
[/(s)eries$/i, '$1eries'],
[/(m)ovies$/i, '$1ovie'],
[/(x|ch|ss|sh)es$/i, '$1'],
[/^(m|l)ice$/i, '$1ouse'],
[/(bus)(es)?$/i, '$1'],
[/(o)es$/i, '$1'],
[/(shoe)s$/i, '$1'],
[/(cris|test)(is|es)$/i, '$1is'],
[/^(a)x[ie]s$/i, '$1xis'],
[/(octop|vir)(us|i)$/i, '$1us'],
[/(alias|status)(es)?$/i, '$1'],
[/^(ox)en/i, '$1'],
[/(vert|ind)ices$/i, '$1ex'],
[/(matr)ices$/i, '$1ix'],
[/(quiz)zes$/i, '$1'],
[/(database)s$/i, '$1']
],
irregularPairs: [
['person', 'people'],
['man', 'men'],
['child', 'children'],
['sex', 'sexes'],
['move', 'moves'],
['cow', 'kine'],
['zombie', 'zombies']
],
uncountable: [
'equipment',
'information',
'rice',
'money',
'species',
'series',
'fish',
'sheep',
'jeans',
'police'
]
};
__exports__["default"] = defaultRules;
});
define("ember-inflector/lib/system/inflector",
["exports"],
function(__exports__) {
"use strict";
var BLANK_REGEX = /^\s*$/;
function loadUncountable(rules, uncountable) {
for (var i = 0, length = uncountable.length; i < length; i++) {
rules.uncountable[uncountable[i].toLowerCase()] = true;
}
}
function loadIrregular(rules, irregularPairs) {
var pair;
for (var i = 0, length = irregularPairs.length; i < length; i++) {
pair = irregularPairs[i];
rules.irregular[pair[0].toLowerCase()] = pair[1];
rules.irregularInverse[pair[1].toLowerCase()] = pair[0];
}
}
/**
Inflector.Ember provides a mechanism for supplying inflection rules for your
application. Ember includes a default set of inflection rules, and provides an
API for providing additional rules.
Examples:
Creating an inflector with no rules.
```js
var inflector = new Ember.Inflector();
```
Creating an inflector with the default ember ruleset.
```js
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('cow') //=> 'kine'
inflector.singularize('kine') //=> 'cow'
```
Creating an inflector and adding rules later.
```javascript
var inflector = Ember.Inflector.inflector;
inflector.pluralize('advice') // => 'advices'
inflector.uncountable('advice');
inflector.pluralize('advice') // => 'advice'
inflector.pluralize('formula') // => 'formulas'
inflector.irregular('formula', 'formulae');
inflector.pluralize('formula') // => 'formulae'
// you would not need to add these as they are the default rules
inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');
```
Creating an inflector with a nondefault ruleset.
```javascript
var rules = {
plurals: [ /$/, 's' ],
singular: [ /\s$/, '' ],
irregularPairs: [
[ 'cow', 'kine' ]
],
uncountable: [ 'fish' ]
};
var inflector = new Ember.Inflector(rules);
```
@class Inflector
@namespace Ember
*/
function Inflector(ruleSet) {
ruleSet = ruleSet || {};
ruleSet.uncountable = ruleSet.uncountable || {};
ruleSet.irregularPairs = ruleSet.irregularPairs || {};
var rules = this.rules = {
plurals: ruleSet.plurals || [],
singular: ruleSet.singular || [],
irregular: {},
irregularInverse: {},
uncountable: {}
};
loadUncountable(rules, ruleSet.uncountable);
loadIrregular(rules, ruleSet.irregularPairs);
}
Inflector.prototype = {
/**
@method plural
@param {RegExp} regex
@param {String} string
*/
plural: function(regex, string) {
this.rules.plurals.push([regex, string.toLowerCase()]);
},
/**
@method singular
@param {RegExp} regex
@param {String} string
*/
singular: function(regex, string) {
this.rules.singular.push([regex, string.toLowerCase()]);
},
/**
@method uncountable
@param {String} regex
*/
uncountable: function(string) {
loadUncountable(this.rules, [string.toLowerCase()]);
},
/**
@method irregular
@param {String} singular
@param {String} plural
*/
irregular: function (singular, plural) {
loadIrregular(this.rules, [[singular, plural]]);
},
/**
@method pluralize
@param {String} word
*/
pluralize: function(word) {
return this.inflect(word, this.rules.plurals, this.rules.irregular);
},
/**
@method singularize
@param {String} word
*/
singularize: function(word) {
return this.inflect(word, this.rules.singular, this.rules.irregularInverse);
},
/**
@protected
@method inflect
@param {String} word
@param {Object} typeRules
@param {Object} irregular
*/
inflect: function(word, typeRules, irregular) {
var inflection, substitution, result, lowercase, isBlank,
isUncountable, isIrregular, isIrregularInverse, rule;
isBlank = BLANK_REGEX.test(word);
if (isBlank) {
return word;
}
lowercase = word.toLowerCase();
isUncountable = this.rules.uncountable[lowercase];
if (isUncountable) {
return word;
}
isIrregular = irregular && irregular[lowercase];
if (isIrregular) {
return isIrregular;
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i-1];
rule = inflection[0];
if (rule.test(word)) {
break;
}
}
inflection = inflection || [];
rule = inflection[0];
substitution = inflection[1];
result = word.replace(rule, substitution);
return result;
}
};
__exports__["default"] = Inflector;
});
define("ember-inflector/lib/system/string",
["./inflector","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Inflector = __dependency1__["default"];
var pluralize = function(word) {
return Inflector.inflector.pluralize(word);
};
var singularize = function(word) {
return Inflector.inflector.singularize(word);
};
__exports__.pluralize = pluralize;
__exports__.singularize = singularize;
});
global.DS = requireModule('ember-data/lib/main')['default'];
}(window)); |
app/main.js | wojciech-panek/study-group-7-ssr | /* eslint-disable */
/**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
// Import all the third party stuff
import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import createHistory from 'history/createBrowserHistory';
import { ConnectedRouter, syncHistoryWithStore } from 'react-router-redux';
import injectTapEventPlugin from 'react-tap-event-plugin'
import 'ScrollToPlugin';
import rootSaga from './modules/sagas';
import FontFaceObserver from 'fontfaceobserver';
import 'normalize.css/normalize.css';
import './main.scss';
// Import selector for `syncHistoryWithStore`
import { selectLocationState } from './modules/router/router.selectors';
import configureStore from './modules/store';
// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});
// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
document.body.classList.add('fontLoaded');
}, () => {
document.body.classList.remove('fontLoaded');
});
// Needed for onTouchTap
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const browserHistory = createHistory();
const initialState = window.APP_STATE;
const store = configureStore(initialState, browserHistory);
delete window.APP_STATE;
store.runSaga(rootSaga);
if (process.env.NODE_ENV === 'development') {
const DevToolsComponent = require('./utils/devtools.component').default;
const devToolsRoot = window.document.createElement('div');
window.document.body.appendChild(devToolsRoot);
ReactDOM.render(
<Provider store={store}>
<DevToolsComponent />
</Provider>,
devToolsRoot
);
}
const render = () => {
const NextApp = require('./routes').default;
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<ConnectedRouter history={browserHistory}>
<NextApp userAgent={navigator.userAgent} />
</ConnectedRouter>
</Provider>
</AppContainer>,
document.getElementById('app')
);
};
if (!window.Intl) {
(new Promise((resolve) => {
resolve(require('intl'));
}))
.then(() => Promise.all([
require('intl/locale-data/jsonp/en.js'),
require('intl/locale-data/jsonp/de.js'),
]))
.then(() => render())
.catch((err) => {
throw err;
});
} else {
render();
}
if (module.hot) {
module.hot.accept('./routes', () => {
render();
});
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require, import/no-extraneous-dependencies
}
|
ajax/libs/rxjs/2.4.10/rx.lite.compat.js | arasmussen/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) {
var len = arr.length, a = new Array(len);
for(var i = 0; i < len; i++) { a[i] = arr[i]; }
return a;
}
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Error.prototype;
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Error.prototype;
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Error.prototype;
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Error.prototype;
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Error.prototype;
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
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 = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
}
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
!item.isCancelled() && item.invoke();
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
return currentScheduler;
}());
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle) }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { return thrower(result.e); }
}
}
}
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
runTask(event.data.substring(MSG_PREFIX.length));
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this, dt = Scheduler.normalize(dueTime);
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function(err) { o.onError(err); },
self)
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return observer.onError(ex);
}
if (currentItem.done) {
if (lastException !== null) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
if (selector) {
var selectorFn = bindCallback(selector, thisArg, 3);
}
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
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 ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ToArrayObserver(observer));
};
return ToArrayObservable;
}(ObservableBase));
function ToArrayObserver(observer) {
this.observer = observer;
this.a = [];
this.isStopped = false;
}
ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
ToArrayObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
}
};
ToArrayObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onNext(this.a);
this.observer.onCompleted();
}
};
ToArrayObserver.prototype.dispose = function () { this.isStopped = true; }
ToArrayObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(null, function () {
observer.onCompleted();
});
});
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (observer) {
var sink = new FromSink(observer, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
observer = this.observer,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
try {
var next = it.next();
} catch (e) {
return observer.onError(e);
}
if (next.done) {
return observer.onCompleted();
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
return observer.onError(e);
}
}
observer.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursiveWithState(0, function (idx, self) {
if (idx < len) {
var key = keys[idx];
observer.onNext([key, obj[key]]);
self(idx + 1);
} else {
observer.onCompleted();
}
});
});
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.count = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.count, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just' or browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(value, function (_, v) {
observer.onNext(v);
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} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) {
try {
var result = handler(e);
} catch (ex) {
return o.onError(ex);
}
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(o));
}, function (x) { o.onCompleted(x); }));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop();
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
falseFactory = function () { return false; },
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return enumerableOf(args).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
return MergeAllObservable;
}(ObservableBase));
var MergeAllObserver = (function() {
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, g, sad) {
this.parent = parent;
this.g = g;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = observableProto.mergeObservable = function () {
return new MergeAllObservable(this);
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(o),
other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop)
);
}, source);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
*
* @example
* 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
if (typeof source === 'undefined') {
throw new Error('Source observable not found for withLatestFrom().');
}
if (typeof resultSelector !== 'function') {
throw new Error('withLatestFrom() expects a resultSelector function.');
}
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, observer.onError.bind(observer), function () {}));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var res;
var allValues = [x].concat(values);
if (!hasValueAll) return;
try {
res = resultSelector.apply(null, allValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}, observer.onError.bind(observer), function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
return observer.onError(e);
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, function (e) { observer.onError(e); }, function () { observer.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources;
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, this);
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
try {
key = keySelector(value);
} catch (e) {
o.onError(e);
return;
}
}
if (hasCurrentKey) {
try {
var comparerEquals = comparer(currentKey, key);
} catch (e) {
o.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return source.subscribe(function (x) {
try {
tapObserver.onNext(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
try {
tapObserver.onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}, function () {
try {
tapObserver.onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
});
}, this);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
o.onNext(accumulation);
},
function (e) { o.onError(e); },
function () {
!hasValue && hasSeed && o.onNext(seed);
o.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
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; });
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
var self = this;
return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg)
};
MapObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new MapObserver(observer, this.selector, this));
};
return MapObservable;
}(ObservableBase));
function MapObserver(observer, selector, source) {
this.observer = observer;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
MapObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector).call(this, x, this.i++, this.source);
if (result === errorObj) {
return this.observer.onError(result.e);
}
this.observer.onNext(result);
};
MapObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
MapObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
MapObserver.prototype.dispose = function() { this.isStopped = true; };
MapObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
o.onNext(x);
} else {
remaining--;
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining === 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new FilterObserver(observer, this.predicate, this));
};
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
var self = this;
return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg);
};
return FilterObservable;
}(ObservableBase));
function FilterObserver(observer, predicate, source) {
this.observer = observer;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
FilterObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.observer.onError(shouldYield.e);
}
shouldYield && this.observer.onNext(x);
};
FilterObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
FilterObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
FilterObserver.prototype.dispose = function() { this.isStopped = true; };
FilterObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
/**
* 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 (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var len = arguments.length, results = [];
for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
if (selector) {
try {
results = selector(results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = root.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation) {
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch (event.type) {
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
}
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette, Ember.js
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param windowSize [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var 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);
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
o.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
o.onError(ex);
return;
}
o.onNext(res);
}
if (isDone && values[1]) {
o.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
o.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
o.onNext(q.shift());
}
o.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
o.onNext(q.shift());
}
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onCompleted();
else
this.queue.push(Rx.Notification.createOnCompleted());
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onError(error);
else
this.queue.push(Rx.Notification.createOnError(error));
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value));
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while ((this.queue.length >= numberOfItems && numberOfItems > 0) ||
(this.queue.length > 0 && this.queue[0].kind !== 'N')) {
var first = this.queue.shift();
first.accept(this.subject);
if (first.kind === 'N') numberOfItems--;
else { this.disposeCurrentRequest(); this.queue = []; }
}
return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0};
}
//TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function
//if (this.hasFailed) {
// this.subject.onError(this.error);
//} else if (this.hasCompleted) {
// this.subject.onCompleted();
//}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable;
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
var sub = tryCatch(subscribe)(ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(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));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Gets the current value or throws an exception.
* Value is frozen after onCompleted is called.
* After onError is called always throws the specified exception.
* An exception is always thrown after dispose is called.
* @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
*/
getValue: function () {
checkDisposed(this);
if (this.hasError) {
throw this.error;
}
return this.value;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
/**
* 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));
|
static/src/js/containers/dev_tools.js | talp101/messenger | import React from 'react';
// Exported from redux-devtools
import { createDevTools } from 'redux-devtools';
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
// createDevTools takes a monitor and produces a DevTools component
const DevTools = createDevTools(
// Monitors are individually adjustable with props.
// Consult their repositories to learn about those props.
// Here, we put LogMonitor inside a DockMonitor.
// Note: DockMonitor is visible by default.
<DockMonitor toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'
defaultIsVisible={true}>
<LogMonitor theme='tomorrow' />
</DockMonitor>
);
export default DevTools; |
ajax/libs/rxjs/2.1.10/rx.modern.js | liubo404/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
(function (window, undefined) {
var freeExports = typeof exports == 'object' && exports,
freeModule = typeof module == 'object' && module && module.exports == freeExports && module,
freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal) {
window = freeGlobal;
}
/**
* @name Rx
* @type Object
*/
var Rx = { Internals: {} };
// Defaults
function noop() { }
function identity(x) { return x; }
function defaultNow() { return new Date().getTime(); }
function defaultComparer(x, y) { return isEqual(x, y); }
function defaultSubComparer(x, y) { return x - y; }
function defaultKeySerializer(x) { return x.toString(); }
function defaultError(err) { throw err; }
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() {
if (this.isDisposed) {
throw new Error(objectDisposed);
}
}
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.Internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
var result;
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined`, avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor,
ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB && !(
isFunction(ctorA) && ctorA instanceof ctorA &&
isFunction(ctorB) && ctorB instanceof ctorB
)) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
length = a.length;
size = b.length;
// compare lengths to determine if a deep comparison is necessary
result = size == a.length;
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
return result;
}
// deep compare each object
for(var key in b) {
if (hasOwnProperty.call(b, key)) {
// count properties and deep compare each property value
size++;
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB));
}
}
if (result) {
// ensure both objects have the same number of properties
for (var key in a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.Internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.Internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () {
return this.items[0].value;
};
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
*
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
*
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
*
* @memberOf CompositeDisposable#
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*
* @memberOf CompositeDisposable#
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*
* @memberOf CompositeDisposable#
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
*
* @memberOf CompositeDisposable#
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
*
* @memberOf CompositeDisposable#
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/**
* Performs the task of cleaning up resources.
*
* @memberOf Disposable#
*/
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
*
* @static
* @memberOf Disposable
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*
* @static
* @memberOf Disposable
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*
* @constructor
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
this.isDisposed = false;
this.current = null;
};
var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype;
/**
* Gets or sets the underlying disposable. After disposal, the result of getting this method is undefined.
*
* @memberOf SingleAssignmentDisposable#
* @param {Disposable} [value] The new underlying disposable.
* @returns {Disposable} The underlying disposable.
*/
SingleAssignmentDisposablePrototype.disposable = function (value) {
return !value ? this.getDisposable() : this.setDisposable(value);
};
/**
* Gets the underlying disposable. After disposal, the result of getting this method is undefined.
*
* @memberOf SingleAssignmentDisposable#
* @returns {Disposable} The underlying disposable.
*/
SingleAssignmentDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
*
* @memberOf SingleAssignmentDisposable#
* @param {Disposable} value The new underlying disposable.
*/
SingleAssignmentDisposablePrototype.setDisposable = function (value) {
if (this.current) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
this.current = value;
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Disposes the underlying disposable.
*
* @memberOf SingleAssignmentDisposable#
*/
SingleAssignmentDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*
* @constructor
*/
var SerialDisposable = Rx.SerialDisposable = function () {
this.isDisposed = false;
this.current = null;
};
/**
* Gets the underlying disposable.
* @return The underlying disposable</returns>
*/
SerialDisposable.prototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
*
* @memberOf SerialDisposable#
* @param {Disposable} value The new underlying disposable.
*/
SerialDisposable.prototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
if (old) {
old.dispose();
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Gets or sets the underlying disposable.
* If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object.
*
* @memberOf SerialDisposable#
* @param {Disposable} [value] The new underlying disposable.
* @returns {Disposable} The underlying disposable.
*/
SerialDisposable.prototype.disposable = function (value) {
if (!value) {
return this.getDisposable();
} else {
this.setDisposable(value);
}
};
/**
* Disposes the underlying disposable as well as all future replacements.
*
* @memberOf SerialDisposable#
*/
SerialDisposable.prototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
/**
* @constructor
* @private
*/
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
/** @private */
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
*
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*
* @memberOf RefCountDisposable#
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
*
* @memberOf RefCountDisposable#
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.H
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
/**
* @constructor
* @private
*/
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false;
}
/**
* @private
* @memberOf ScheduledDisposable#
*/
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
/**
* @private
* @constructor
*/
function ScheduledItem(scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
/**
* @private
* @memberOf ScheduledItem#
*/
ScheduledItem.prototype.invoke = function () {
this.disposable.disposable(this.invokeCore());
};
/**
* @private
* @memberOf ScheduledItem#
*/
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
/**
* @private
* @memberOf ScheduledItem#
*/
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
/**
* @private
* @memberOf ScheduledItem#
*/
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
/**
* @constructor
* @private
*/
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
*
* @memberOf Scheduler#
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchException = function (handler) {
return new CatchScheduler(this, handler);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
*
* @memberOf Scheduler#
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, function () {
action();
});
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
*
* @memberOf Scheduler#
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodicWithState = function (state, period, action) {
var s = state, id = window.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
window.clearInterval(id);
});
};
/**
* Schedules an action to be executed.
*
* @memberOf Scheduler#
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
*
* @memberOf Scheduler#
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
*
* @memberOf Scheduler#
* @param {Function} action Action to execute.
* @param {Number}dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
*
* @memberOf Scheduler#
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
*
* @memberOf Scheduler#
* @param {Function} action Action to execute.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
*
* @memberOf Scheduler#
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
*
* @memberOf Scheduler#
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
*
* @memberOf Scheduler#
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
*
* @memberOf Scheduler
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
*
* @memberOf Scheduler
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
*
* @memberOf Scheduler
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
*
* @memberOf Scheduler
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
*
* @static
* @memberOf Scheduler
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var schedulerNoBlockError = 'Scheduler is not allowed to block the thread';
/**
* Gets a scheduler that schedules work immediately on the current thread.
*
* @memberOf Scheduler
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) {
return action(this, state);
}
function scheduleRelative(state, dueTime, action) {
if (dueTime > 0) throw new Error(schedulerNoBlockError);
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
/**
* @private
* @constructor
*/
function Trampoline() {
queue = new PriorityQueue(4);
}
/**
* @private
* @memberOf Trampoline
*/
Trampoline.prototype.dispose = function () {
queue = null;
};
/**
* @private
* @memberOf Trampoline
*/
Trampoline.prototype.run = function () {
var item;
while (queue.length > 0) {
item = queue.dequeue();
if (!item.isCancelled()) {
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
};
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt),
t;
if (!queue) {
t = new Trampoline();
try {
queue.enqueue(si);
t.run();
} catch (e) {
throw e;
} finally {
t.dispose();
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return queue === null; };
currentScheduler.ensureTrampoline = function (action) {
if (queue === null) {
return this.schedule(action);
} else {
return action();
}
};
return currentScheduler;
}());
/**
* @private
*/
var SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
/**
* @constructor
* @private
*/
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (_super) {
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, _super);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
*
* @memberOf VirtualTimeScheduler#
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
*
* @memberOf VirtualTimeScheduler#
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
*
* @memberOf VirtualTimeScheduler#
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*
* @memberOf VirtualTimeScheduler#
*/
VirtualTimeSchedulerPrototype.start = function () {
var next;
if (!this.isEnabled) {
this.isEnabled = true;
do {
next = this.getNext();
if (next !== null) {
if (this.comparer(next.dueTime, this.clock) > 0) {
this.clock = next.dueTime;
}
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*
* @memberOf VirtualTimeScheduler#
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
*
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var next;
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
if (!this.isEnabled) {
this.isEnabled = true;
do {
next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
if (this.comparer(next.dueTime, this.clock) > 0) {
this.clock = next.dueTime;
}
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
*
* @memberOf VirtualTimeScheduler#
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time);
var dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
return this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
*
* @memberOf VirtualTimeScheduler#
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) {
throw new Error(argumentOutOfRange);
}
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
*
* @memberOf VirtualTimeScheduler#
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
var next;
while (this.queue.length > 0) {
next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
*
* @memberOf VirtualTimeScheduler#
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
*
* @memberOf VirtualTimeScheduler#
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this,
run = function (scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
},
si = new ScheduledItem(self, state, run, dueTime, self.comparer);
self.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (_super) {
inherits(HistoricalScheduler, _super);
/**
* Creates a new historical scheduler with the specified initial clock value.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
_super.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
*
* @memberOf HistoricalScheduler
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
/**
* @private
* @memberOf HistoricalScheduler
*/
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
*
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var scheduleMethod, clearMethod = noop;
(function () {
function postMessageSupported () {
// Ensure not in a worker
if (!window.postMessage || window.importScripts) { return false; }
var isAsync = false,
oldHandler = window.onmessage;
// Test for async
window.onmessage = function () { isAsync = true; };
window.postMessage('','*');
window.onmessage = oldHandler;
return isAsync;
}
// Check for setImmediate first for Node v0.11+
if (!!window.setImmediate && typeof window.setImmediate === 'function') {
scheduleMethod = window.setImmediate;
clearMethod = window.clearImmediate;
} else if (typeof window.process === 'object' && Object.prototype.toString.call(window.process) === '[object process]') {
scheduleMethod = window.process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (window.addEventListener) {
window.addEventListener('message', onGlobalPostMessage, false);
} else {
window.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
window.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!window.MessageChannel) {
var channel = new window.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in window && 'onreadystatechange' in window.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = window.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
window.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return window.setTimeout(action, 0); };
clearMethod = window.clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*
* @memberOf Scheduler
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = window.setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
window.clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @private */
var CatchScheduler = (function (_super) {
function localNow() {
return this._scheduler.now();
}
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, _super);
/** @private */
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
/** @private */
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
/** @private */
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
/** @private */
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
/** @private */
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
var NotificationPrototype = Notification.prototype;
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
return this._acceptObservable(observerOrOnNext);
}
return this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notification
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
NotificationPrototype.toObservable = function (scheduler) {
var notification = this;
scheduler = scheduler || immediateScheduler;
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
if (notification.kind === 'N') {
observer.onCompleted();
}
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
*
* @static
* @memberOf Notification
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) {
return onNext(this.value);
}
function _acceptObservable(observer) {
return observer.onNext(this.value);
}
function toString () {
return 'OnNext(' + this.value + ')';
}
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept.bind(notification);
notification._acceptObservable = _acceptObservable.bind(notification);
notification.toString = toString.bind(notification);
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
*
* @static s
* @memberOf Notification
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) {
return onError(this.exception);
}
function _acceptObservable(observer) {
return observer.onError(this.exception);
}
function toString () {
return 'OnError(' + this.exception + ')';
}
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept.bind(notification);
notification._acceptObservable = _acceptObservable.bind(notification);
notification.toString = toString.bind(notification);
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
*
* @static
* @memberOf Notification
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) {
return onCompleted();
}
function _acceptObservable(observer) {
return observer.onCompleted();
}
function toString () {
return 'OnCompleted()';
}
return function () {
var notification = new Notification('C');
notification._accept = _accept.bind(notification);
notification._acceptObservable = _acceptObservable.bind(notification);
notification.toString = toString.bind(notification);
return notification;
};
}());
/**
* @constructor
* @private
*/
var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) {
this.moveNext = moveNext;
this.getCurrent = getCurrent;
this.dispose = dispose;
};
/**
* @static
* @memberOf Enumerator
* @private
*/
var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) {
var done = false;
dispose || (dispose = noop);
return new Enumerator(function () {
if (done) {
return false;
}
var result = moveNext();
if (!result) {
done = true;
dispose();
}
return result;
}, function () { return getCurrent(); }, function () {
if (!done) {
dispose();
done = true;
}
});
};
/** @private */
var Enumerable = Rx.Internals.Enumerable = (function () {
/**
* @constructor
* @private
*/
function Enumerable(getEnumerator) {
this.getEnumerator = getEnumerator;
}
/**
* @private
* @memberOf Enumerable#
*/
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, ex, hasNext = false;
if (!isDisposed) {
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
} else {
e.dispose();
}
} catch (exception) {
ex = exception;
e.dispose();
}
} else {
return;
}
if (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
observer.onCompleted();
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
e.dispose();
}));
});
};
/**
* @private
* @memberOf Enumerable#
*/
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed = false, lastException;
var subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, ex, hasNext;
hasNext = false;
if (!isDisposed) {
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
}
} catch (exception) {
ex = exception;
}
} else {
return;
}
if (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
return Enumerable;
}());
/**
* @static
* @private
* @memberOf Enumerable
*/
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount === undefined) {
repeatCount = -1;
}
return new Enumerable(function () {
var current, left = repeatCount;
return enumeratorCreate(function () {
if (left === 0) {
return false;
}
if (left > 0) {
left--;
}
current = value;
return true;
}, function () { return current; });
});
};
/**
* @static
* @private
* @memberOf Enumerable
*/
var enumerableFor = Enumerable.forEach = function (source, selector) {
selector || (selector = identity);
return new Enumerable(function () {
var current, index = -1;
return enumeratorCreate(
function () {
if (++index < source.length) {
current = selector(source[index], index);
return true;
}
return false;
},
function () { return current; }
);
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.Internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function () {
if (!this.isStopped) {
this.isStopped = true;
this.error(true);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
*
* @constructor
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
*
* @memberOf AnonymousObserver
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
*
* @memberOf AnonymousObserver
* @param {Any{ error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*
* @memberOf AnonymousObserver
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
/** @private */
var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
/** @private */
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
/** @private */
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
/** @private */
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
/** @private */
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
/** @private */
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/** @private */
var ObserveOnObserver = (function (_super) {
inherits(ObserveOnObserver, _super);
/** @private */
function ObserveOnObserver() {
_super.apply(this, arguments);
}
/** @private */
ObserveOnObserver.prototype.next = function (value) {
_super.prototype.next.call(this, value);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.error = function (e) {
_super.prototype.error.call(this, e);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.completed = function () {
_super.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
/**
* @constructor
* @private
*/
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
observableProto.finalValue = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var hasValue = false, value;
return source.subscribe(function (x) {
hasValue = true;
value = x;
}, observer.onError.bind(observer), function () {
if (!hasValue) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
};
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber;
if (typeof observerOrOnNext === 'object') {
subscriber = observerOrOnNext;
} else {
subscriber = observerCreate(observerOrOnNext, onError, onCompleted);
}
return this._subscribe(subscriber);
};
/**
* Creates a list from an observable sequence.
*
* @memberOf Observable
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
function accumulator(list, i) {
var newList = list.slice(0);
newList.push(i);
return newList;
}
return this.scan([], accumulator).startWith([]).finalValue();
};
return Observable;
})();
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* 1 - res = Rx.Observable.start(function () { console.log('hello'); });
* 2 - res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* 2 - res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, scheduler, context) {
return observableToAsync(func, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
*
* @example
* 1 - res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3);
* 2 - res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3);
* 2 - res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello');
*
* @param function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, scheduler, context) {
scheduler || (scheduler = timeoutScheduler);
return function () {
var args = slice.call(arguments, 0), subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* 1 - res = Rx.Observable.create(function (observer) { return function () { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = function (subscribe) {
return new AnonymousObservable(function (o) {
return disposableCreate(subscribe(o));
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* 1 - res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* @static
* @memberOf Observable
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* 1 - res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @static
* @memberOf Observable
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* 1 - res = Rx.Observable.empty();
* 2 - res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* 1 - res = Rx.Observable.fromArray([1,2,3]);
* 2 - res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0;
return scheduler.scheduleRecursive(function (self) {
if (count < array.length) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* 1 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* 2 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
*
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* 1 - res = Rx.Observable.range(0, 10);
* 2 - res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* 1 - res = Rx.Observable.repeat(42);
* 2 - res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
if (repeatCount == null) {
repeatCount = -1;
}
return observableReturn(value, scheduler).repeat(repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'returnValue' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.return(42);
* 2 - res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.throwException(new Error('Error'));
* 2 - res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
*
* @example
* 1 - res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @static
* @memberOf Observable
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
if (resource) {
disposable = resource;
}
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence that reacts first.
*
* @memberOf Observable#
* @param {Observable} rightSource Second observable sequence.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence that reacts first.
*
* @example
* E.g. winner = Rx.Observable.amb(xs, ys, zs);
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @memberOf Observable#
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto.catchException = function (handlerOrSecond) {
if (typeof handlerOrSecond === 'function') {
return observableCatchHandler(this, handlerOrSecond);
}
return observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @memberOf Observable#
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(function (x) { return x; }))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(function (x) { return x; })) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(args[i].subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @memberOf Observable#
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
*
* @memberOf Observable#
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @memberOf Observable#
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
*
* @static
* @memberOf Observable
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
*
* @memberOf Observable#
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) {
observer.onCompleted();
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @memberOf Observable
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) {
throw new Error('Second observable is required');
}
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {
self();
}, function () {
self();
}));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
*
* @memberOf Observable#
* @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
if (isOpen) {
observer.onNext(left);
}
}, observer.onError.bind(observer), function () {
if (isOpen) {
observer.onCompleted();
}
}));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
*
* @memberOf Observable#
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
*
* @memberOf Observable#
* @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @memberOf Observable#
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
var next = function (i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
*
* @static
* @memberOf Observable
* @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.
*
* @static
* @memberOf Observable
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = slice.call(arguments);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
*
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* 1 - xs.bufferWithCount(10);
* 2 - xs.bufferWithCount(10, 1);
*
* @memberOf Observable#
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (skip === undefined) {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
*
* @memberOf Observable#
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* 1 - var obs = observable.distinctUntilChanged();
* 2 - var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* 3 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @memberOf Observable#
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* 1 - observable.doAction(observer);
* 2 - observable.doAction(onNext);
* 3 - observable.doAction(onNext, onError);
* 4 - observable.doAction(onNext, onError, onCompleted);
*
* @memberOf Observable#
* @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (exception) {
if (!onError) {
observer.onError(exception);
} else {
try {
onError(exception);
} catch (e) {
observer.onError(e);
}
observer.onError(exception);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* 1 - obs = observable.finallyAction(function () { console.log('sequence ended'; });
*
* @memberOf Observable#
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = source.subscribe(observer);
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
*
* @memberOf Observable#
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
*
* @memberOf Observable#
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (exception) {
observer.onNext(notificationCreateOnError(exception));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* 1 - repeated = source.repeat();
* 2 - repeated = source.repeat(42);
*
* @memberOf Observable#
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
*
* @example
* 1 - retried = retry.repeat();
* 2 - retried = retry.repeat(42);
*
* @memberOf Observable#
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
*
* 1 - scanned = source.scan(function (acc, x) { return acc + x; });
* 2 - scanned = source.scan(0, function (acc, x) { return acc + x; });
*
* @memberOf Observable#
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var seed, hasSeed = false, accumulator;
if (arguments.length === 2) {
seed = arguments[0];
accumulator = arguments[1];
hasSeed = true;
} else {
accumulator = arguments[0];
}
var source = this;
return observableDefer(function () {
var hasAccumulation = false, accumulation;
return source.select(function (x) {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
return accumulation;
});
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
*
* @memberOf Observable#
* @description
* This operator accumulates a queue with a length enough to store the first <paramref name="count"/> elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* 1 - source.startWith(1, 2, 3);
* 2 - source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
*
* @example
* 1 - obs = source.takeLast(5);
* 2 - obs = source.takeLast(5, Rx.Scheduler.timeout);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
*
* @memberOf Observable#
* @param {Number} count Number of elements to take from the end of the source sequence.
* @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count, scheduler) {
return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
*
* @memberOf Observable#
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
q.shift();
}
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* 1 - xs.windowWithCount(10);
* 2 - xs.windowWithCount(10, 1);
*
* @memberOf Observable#
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
if (count <= 0) {
throw new Error(argumentOutOfRange);
}
if (skip == null) {
skip = count;
}
if (skip <= 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [],
createWindow = function () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
};
createWindow();
m.setDisposable(source.subscribe(function (x) {
var s;
for (var i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
var c = n - count + 1;
if (c >= 0 && c % skip === 0) {
s = q.shift();
s.onCompleted();
}
n++;
if (n % skip === 0) {
createWindow();
}
}, function (exception) {
while (q.length > 0) {
q.shift().onError(exception);
}
observer.onError(exception);
}, function () {
while (q.length > 0) {
q.shift().onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* 1 - obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* 1 - obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); });
*
* @memberOf Observable#
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, keySerializer) {
var source = this;
keySelector || (keySelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var hashSet = {};
return source.subscribe(function (x) {
var key, serializedKey, otherKey, hasMatch = false;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (exception) {
observer.onError(exception);
return;
}
for (otherKey in hashSet) {
if (serializedKey === otherKey) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
hashSet[serializedKey] = null;
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* 1 - observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
*
* @memberOf Observable#
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, keySerializer) {
return this.groupByUntil(keySelector, elementSelector, function () {
return observableNever();
}, keySerializer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* 1 - observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
*
* @memberOf Observable#
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) {
var source = this;
elementSelector || (elementSelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var map = {},
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
fireNewMapEntry = false;
try {
writer = map[serializedKey];
if (!writer) {
writer = new Subject();
map[serializedKey] = writer;
fireNewMapEntry = true;
}
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
if (fireNewMapEntry) {
group = new GroupedObservable(key, writer, refCountDisposable);
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
observer.onNext(group);
md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
if (serializedKey in map) {
delete map[serializedKey];
writer.onCompleted();
}
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(noop, function (exn) {
for (w in map) {
map[w].onError(exn);
}
observer.onError(exn);
}, function () {
expire();
}));
}
try {
element = elementSelector(x);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
for (var w in map) {
map[w].onError(ex);
}
observer.onError(ex);
}, function () {
for (var w in map) {
map[w].onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
*
* @example
* source.select(function (value, index) { return value * value + index; });
*
* @memberOf Observable#
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
observableProto.map = observableProto.select;
function selectMany(selector) {
return this.select(selector).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* 1 - source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* 1 - source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* 1 - source.selectMany(Rx.Observable.fromArray([1,2,3]));
*
* @memberOf Observable#
* @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.selectMany(function (x) {
return selector(x).select(function (y) {
return resultSelector(x, y);
});
});
}
if (typeof selector === 'function') {
return selectMany.call(this, selector);
}
return selectMany.call(this, function () {
return selector;
});
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
*
* @memberOf Observable#
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* 1 - source.skipWhile(function (value) { return value < 10; });
* 1 - source.skipWhile(function (value, index) { return value < 10 || index < 10; });
*
* @memberOf Observable#
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate(x, i++);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* 1 - source.take(5);
* 2 - source.take(0, Rx.Scheduler.timeout);
*
* @memberOf Observable#
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* 1 - source.takeWhile(function (value) { return value < 10; });
* 1 - source.takeWhile(function (value, index) { return value < 10 || index < 10; });
*
* @memberOf Observable#
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate(x, i++);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* 1 - source.where(function (value) { return value < 10; });
* 1 - source.where(function (value, index) { return value < 10 || index < 10; });
*
* @memberOf Observable#
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
observableProto.filter = observableProto.where;
/** @private */
var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) {
inherits(AnonymousObservable, _super);
/**
* @private
* @constructor
*/
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(function () {
try {
autoDetachObserver.disposable(subscribe(autoDetachObserver));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
});
} else {
try {
autoDetachObserver.disposable(subscribe(autoDetachObserver));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
}
return autoDetachObserver;
}
_super.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
/**
* @private
* @constructor
*/
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.disposable = function (value) {
return this.m.disposable(value);
};
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var GroupedObservable = (function (_super) {
inherits(GroupedObservable, _super);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
/**
* @constructor
* @private
*/
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
_super.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
*
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
*
* @memberOf ReplaySubject#
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*
* @memberOf ReplaySubject#
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
*
* @memberOf ReplaySubject#
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
*
* @memberOf ReplaySubject#
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*
* @memberOf ReplaySubject#
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
*
* @static
* @memberOf Subject
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
var hv = this.hasValue;
var v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
*
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.value = null,
this.hasValue = false,
this.observers = [],
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
*
* @memberOf AsyncSubject#
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*
* @memberOf AsyncSubject#
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
var v = this.value;
var hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
*
* @memberOf AsyncSubject#
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
*
* @memberOf AsyncSubject#
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*
* @memberOf AsyncSubject#
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
/** @private */
var AnonymousSubject = (function (_super) {
inherits(AnonymousSubject, _super);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
/**
* @private
* @constructor
*/
function AnonymousSubject(observer, observable) {
_super.call(this, subscribe);
this.observer = observer;
this.observable = observable;
}
addProperties(AnonymousSubject.prototype, Observer, {
/**
* @private
* @memberOf AnonymousSubject#
*/
onCompleted: function () {
this.observer.onCompleted();
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onError: function (exception) {
this.observer.onError(exception);
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
// Check for AMD
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
window.Rx = Rx;
return define(function () {
return Rx;
});
} else if (freeExports) {
if (typeof module == 'object' && module && module.exports == freeExports) {
module.exports = Rx;
} else {
freeExports = Rx;
}
} else {
window.Rx = Rx;
}
}(this)); |
app/javascript/flavours/glitch/features/notifications/components/column_settings.js | im-in-space/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import ClearColumnButton from './clear_column_button';
import GrantPermissionButton from './grant_permission_button';
import SettingToggle from './setting_toggle';
import PillBarButton from './pill_bar_button';
import { isStaff } from 'flavours/glitch/util/initial_state';
export default class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
pushSettings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
onRequestNotificationPermission: PropTypes.func,
alertsEnabled: PropTypes.bool,
browserSupport: PropTypes.bool,
browserPermission: PropTypes.bool,
};
onPushChange = (path, checked) => {
this.props.onChange(['push', ...path], checked);
}
render () {
const { settings, pushSettings, onChange, onClear, alertsEnabled, browserSupport, browserPermission, onRequestNotificationPermission } = this.props;
const unreadMarkersShowStr = <FormattedMessage id='notifications.column_settings.unread_notifications.highlight' defaultMessage='Highlight unread notifications' />;
const filterBarShowStr = <FormattedMessage id='notifications.column_settings.filter_bar.show_bar' defaultMessage='Show filter bar' />;
const filterAdvancedStr = <FormattedMessage id='notifications.column_settings.filter_bar.advanced' defaultMessage='Display all categories' />;
const alertStr = <FormattedMessage id='notifications.column_settings.alert' defaultMessage='Desktop notifications' />;
const showStr = <FormattedMessage id='notifications.column_settings.show' defaultMessage='Show in column' />;
const soundStr = <FormattedMessage id='notifications.column_settings.sound' defaultMessage='Play sound' />;
const showPushSettings = pushSettings.get('browserSupport') && pushSettings.get('isSubscribed');
const pushStr = showPushSettings && <FormattedMessage id='notifications.column_settings.push' defaultMessage='Push notifications' />;
return (
<div>
{alertsEnabled && browserSupport && browserPermission === 'denied' && (
<div className='column-settings__row column-settings__row--with-margin'>
<span className='warning-hint'><FormattedMessage id='notifications.permission_denied' defaultMessage='Desktop notifications are unavailable due to previously denied browser permissions request' /></span>
</div>
)}
{alertsEnabled && browserSupport && browserPermission === 'default' && (
<div className='column-settings__row column-settings__row--with-margin'>
<span className='warning-hint'>
<FormattedMessage id='notifications.permission_required' defaultMessage='Desktop notifications are unavailable because the required permission has not been granted.' /> <GrantPermissionButton onClick={onRequestNotificationPermission} />
</span>
</div>
)}
<div className='column-settings__row'>
<ClearColumnButton onClick={onClear} />
</div>
<div role='group' aria-labelledby='notifications-unread-markers'>
<span id='notifications-unread-markers' className='column-settings__section'>
<FormattedMessage id='notifications.column_settings.unread_notifications.category' defaultMessage='Unread notifications' />
</span>
<div className='column-settings__row'>
<SettingToggle id='unread-notification-markers' prefix='notifications' settings={settings} settingPath={['showUnread']} onChange={onChange} label={unreadMarkersShowStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-filter-bar'>
<span id='notifications-filter-bar' className='column-settings__section'>
<FormattedMessage id='notifications.column_settings.filter_bar.category' defaultMessage='Quick filter bar' />
</span>
<div className='column-settings__row'>
<SettingToggle id='show-filter-bar' prefix='notifications' settings={settings} settingPath={['quickFilter', 'show']} onChange={onChange} label={filterBarShowStr} />
<SettingToggle id='show-filter-bar' prefix='notifications' settings={settings} settingPath={['quickFilter', 'advanced']} onChange={onChange} label={filterAdvancedStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-follow'>
<span id='notifications-follow' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow' defaultMessage='New followers:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'follow']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'follow']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-follow-request'>
<span id='notifications-follow-request' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow_request' defaultMessage='New follow requests:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow_request']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow_request']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'follow_request']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'follow_request']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-favourite'>
<span id='notifications-favourite' className='column-settings__section'><FormattedMessage id='notifications.column_settings.favourite' defaultMessage='Favourites:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'favourite']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'favourite']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'favourite']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'favourite']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-mention'>
<span id='notifications-mention' className='column-settings__section'><FormattedMessage id='notifications.column_settings.mention' defaultMessage='Mentions:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'mention']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'mention']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'mention']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'mention']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-reblog'>
<span id='notifications-reblog' className='column-settings__section'><FormattedMessage id='notifications.column_settings.reblog' defaultMessage='Boosts:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'reblog']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'reblog']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'reblog']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-poll'>
<span id='notifications-poll' className='column-settings__section'><FormattedMessage id='notifications.column_settings.poll' defaultMessage='Poll results:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'poll']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'poll']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'poll']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'poll']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-status'>
<span id='notifications-status' className='column-settings__section'><FormattedMessage id='notifications.column_settings.status' defaultMessage='New posts:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'status']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'status']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'status']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'status']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-update'>
<span id='notifications-update' className='column-settings__section'><FormattedMessage id='notifications.column_settings.update' defaultMessage='Edits:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'update']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'update']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'update']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'update']} onChange={onChange} label={soundStr} />
</div>
</div>
{isStaff && (
<div role='group' aria-labelledby='notifications-admin-sign-up'>
<span id='notifications-status' className='column-settings__section'><FormattedMessage id='notifications.column_settings.admin.sign_up' defaultMessage='New sign-ups:' /></span>
<div className='column-settings__pillbar'>
<PillBarButton disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'admin.sign_up']} onChange={onChange} label={alertStr} />
{showPushSettings && <PillBarButton prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'admin.sign_up']} onChange={this.onPushChange} label={pushStr} />}
<PillBarButton prefix='notifications' settings={settings} settingPath={['shows', 'admin.sign_up']} onChange={onChange} label={showStr} />
<PillBarButton prefix='notifications' settings={settings} settingPath={['sounds', 'admin.sign_up']} onChange={onChange} label={soundStr} />
</div>
</div>
)}
</div>
);
}
}
|
src/pages/raspberry.js | LDinho/YogieBerry | import React from 'react'
import Link from 'gatsby-link'
import IndexPage from './index.js'
import raspberry from '../../public/images/Raspberry_flavor_600x390.jpg'
import '../layouts/flavors.css'
const Raspberry = () =>
<div>
<IndexPage />
<h1
style={{
color: '#7EBF00',
fontWeight: '500',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>Frozen Yogurt Flavors
</h1>
<div
style={{
fontFamily: 'sans-serif',
fontSize: 30,
fontWeight: '700',
display: 'flex',
flexDirection: 'column-reverse',
alignItems: 'center',
}}
>
<Link to="/flavors/" style={{fontSize: 16, textDecoration: 'none', color:'#7EBF00'}}>back to menu</Link>
<p>black raspberry</p>
<img src={raspberry} alt="raspberry" />
</div>
</div>;
export default Raspberry
|
src/esm/components/graphics/icons-next/instagram-icon-next/index.js | KissKissBankBank/kitten | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["color", "title"];
import React from 'react';
import PropTypes from 'prop-types';
export var InstagramIconNext = function InstagramIconNext(_ref) {
var color = _ref.color,
title = _ref.title,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement("svg", _extends({
width: "24",
height: "24",
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", {
d: "M23.096 11.996c0 1.612-.033 3.23.009 4.842.07 2.854-1.724 5.06-4.008 6.041a7.247 7.247 0 0 1-2.877.603c-3.118.004-6.24.046-9.359-.014-2.349-.047-4.28-1.029-5.666-2.965C.468 19.483.12 18.325.12 17.069V7.11c0-2.711 1.32-4.606 3.665-5.838C4.805.738 5.912.51 7.065.506c3.026 0 6.056-.018 9.081.01 2.349.018 4.309.917 5.754 2.807.806 1.056 1.196 2.27 1.196 3.605v5.068Zm-21.266 0v5.097c0 .76.176 1.473.57 2.117 1.033 1.691 2.594 2.516 4.53 2.548 3.11.047 6.223.019 9.337.01.764 0 1.505-.158 2.196-.487 1.88-.899 2.932-2.33 2.923-4.48-.018-3.29-.005-6.58-.005-9.869a4.18 4.18 0 0 0-.815-2.534c-1.066-1.441-2.539-2.15-4.3-2.168-3.104-.038-6.208-.014-9.312-.01a5.47 5.47 0 0 0-1.923.366c-1.705.635-3.29 2.243-3.215 4.61.055 1.603.014 3.202.014 4.8Z",
fill: color
}), /*#__PURE__*/React.createElement("path", {
d: "M11.633 16.907c-2.988 0-5.397-2.381-5.402-5.346-.005-2.92 2.423-5.31 5.393-5.31 2.979-.005 5.397 2.381 5.402 5.324 0 2.937-2.414 5.328-5.393 5.332Zm0-1.714c2.034 0 3.684-1.626 3.679-3.628-.005-1.983-1.654-3.604-3.679-3.604-2.034 0-3.692 1.617-3.692 3.614.004 2.001 1.658 3.623 3.692 3.618ZM17.652 4.63c.625 0 1.135.532 1.135 1.186-.005.653-.519 1.181-1.144 1.176-.617-.004-1.122-.532-1.122-1.172-.004-.653.505-1.19 1.131-1.19Z",
fill: color
}));
};
InstagramIconNext.propTypes = {
color: PropTypes.string,
title: PropTypes.string
};
InstagramIconNext.defaultProps = {
color: '#fff',
title: null
}; |
analytics-ui/dev/js/components/header/headerMain.js | CloudBoost/cloudboost | import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {
initApp,
fetchAllEvents,
updateBeacon,
updateNotificationsSeen,
deleteNotificationById,
getNotifications,
logOut
} from '../../actions';
import {DropDownMenu, MenuItem, IconButton, Popover,} from 'material-ui';
import {Toolbar, ToolbarGroup} from 'material-ui/Toolbar';
import NotificationsModal from './notifications/notification';
import FeedbackModal from './feedback/feedback';
import _ from 'underscore'
export class ToolBar extends React.Component {
constructor(props) {
super(props)
this.state = {
open: false,
appSelector: false,
profileModal: false,
options: false,
value: 1
}
}
static get contextTypes() {
return {router: React.PropTypes.object.isRequired}
}
handleTouchTap = (which, event) => {
event.preventDefault()
this.state[which] = true
this.state.anchorEl = event.currentTarget
this.setState(this.state);
// close the already opened popver after opening profile modal
if (which === 'profileModal')
this.setState({open: false})
};
handleChange = (event, index, value) => this.setState({value});
redirectTo(where, noAppId) {
if (noAppId) {
this.context.router.push(ANALYTICS_BASE_URL + where)
} else {
this.context.router.push(ANALYTICS_BASE_URL + this.props.appId + "/" + where)
}
this.handleRequestClose()
}
navigate(appId) {
this.context.router.push(ANALYTICS_BASE_URL + appId)
this.props.initApp(appId);
}
handleRequestClose = () => {
// close all popover
this.setState({open: false, appSelector: false, options: false, profileModal: false})
}
setImgFallbackUrl(e) {
e.target.onError = null;
e.target.src = 'src/assets/img/default-app-icon.png';
}
handleNotificationResponse(type, data) {
if (type === 'addDeveloper') {
this.props.deleteNotificationById(data);
window.location.href = DASHBOARD_URL;
}
else if (type === 'delete') {
this.props.deleteNotificationById(data);
}
this.props.getNotifications()
}
render() {
let userImage = "src/assets/img/user-image.png";
let allApps = [];
if (this.props.user.file)
userImage = this.props.user.file.document.url;
if (this.props.allApps.length && this.props.appId) {
allApps = this.props.allApps.map((app, i) => {
let label = (
<div>
<img height="25px" width="25px"
className="app-selector-img"
src={SERVER_URL + 'appfile/' + app.appId + '/icon'}
onError={this.setImgFallbackUrl}
style={{marginBottom: 3}}
/>
{app.name}
</div>
);
let thisObj = this;
return (
<MenuItem className={app.appId === thisObj.props.appId?'selected-app app-list-item':'app-list-item'}
innerDivStyle={{ "display": "inline-flex", "alignItems": "center" }}
value={i}
primaryText={app.name}
key={i}
label={label}
onClick={this.navigate.bind(this, app.appId)}>
<div height="20px"
className="app-selector-img"
style={{
background: 'url(' + SERVER_URL + 'appfile/' + app.appId + '/icon' + ') , url(src/assets/images/default-app-icon.jpg)',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center center',
height: '20px',
width: '20px'
}}/>
</MenuItem>
);
})
}
let value = 0;
if (this.props.allApps) {
value = _.pluck(this.props.allApps, 'appId').indexOf(this.props.appId);
}
return (
<div id="nav-dash" style={{
backgroundColor: '#FFF',
paddingTop: 2
}}>
<div className="container">
<Toolbar className='toolbar'
style={{backgroundColor: '#FFF'}}>
<ToolbarGroup>
<img className="icon cp"
src="src/assets/img/cblogo.png"
alt="cloud"
onClick={this.redirectTo.bind(this, '', true)}/>
<DropDownMenu value={value}
onChange={this.handleChange}
underlineStyle={{display: "none"}}
listStyle={{'paddingTop': '0px', 'paddingBottom': '0px'}}>
{allApps}
<MenuItem innerDivStyle={{"display": "inline-flex", "alignItems": "center"}}
primaryText={'Dashboard'}
key={9999}
onClick={this.redirectTo.bind(this, '', true)}>
<img height="20px" className="app-selector-img"
src={'..src/assets/img/dashboard-icon.png'}/>
</MenuItem>
</DropDownMenu>
</ToolbarGroup>
<ToolbarGroup>
<FeedbackModal beacons={this.props.beacons}
updateBeacon={this.props.updateBeacon}
user={this.props.user}/>
<IconButton touch={true} onClick={this.handleTouchTap.bind(this, 'options')}>
<svg xmlns="http://www.w3.org/2000/svg"
width="29"
height="29"
viewBox="0 -4 26 26">
<g fill="none" fillRule="evenodd">
<path fill="#9e9e9e"
d="M5.577 3c2.167 0 3.18.846 3.923 2.127v12.288c-.512 0-1.015-.337-1.33-.59-1.03-.828-3.057-.828-5.222-.828H1.945A.944.944 0 0 1 1 15.054V3.946c0-.522.423-.944.945-.944L5.577 3z"/>
<path fill="#AAB7C4"
d="M13.423 3c-2.166 0-3.168.894-3.928 2.107L9.5 17.415c.512 0 1.015-.337 1.33-.59 1.03-.828 3.057-.828 5.222-.828h1.003a.944.944 0 0 0 .945-.945V3.947a.944.944 0 0 0-.945-.945L13.423 3z"/>
</g>
</svg>
</IconButton>
<Popover open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
animated={true}
className="profilepop">
<p className="headingpop">
{ this.props.user.user && this.props.user.user.name &&this.props.user.user.name.toLowerCase() }
</p>
<button className="coloptbtn" onClick={this.handleTouchTap.bind(this, 'profileModal')}>
My Profile
</button>
<button className="coloptbtn" onClick={logOut}>
Logout
</button>
</Popover>
<NotificationsModal updateNotificationsSeen={this.props.updateNotificationsSeen.bind(this)}
handleNotificationResponse={this.handleNotificationResponse.bind(this)}
userId={this.props.user.user._id || ''}
notifications={this.props.notifications || []}/>
<IconButton onClick={this.handleTouchTap.bind(this, 'open')}>
<img className="userhead" src={userImage} alt="User Profile Pic"/>
</IconButton>
</ToolbarGroup>
</Toolbar>
</div>
{/*<Profile open={this.state.profileModal} close={this.handleRequestClose}/>*/}
</div>
)
}
}
function mapStateToProps(state) {
const {
allApps,
appName,
appId,
userProfilePic,
appInitSuccess,
fetchingEvents,
init
} = state.app;
const {user} = state.user;
return {
allApps: allApps || [],
appName,
appId,
userProfilePic,
appInitSuccess,
fetchingEvents,
init,
user,
beacons: state.beacons,
notifications: state.notifications.notifications
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
initApp,
fetchAllEvents,
updateBeacon: (beacons, which) => dispatch(updateBeacon(beacons, which)),
getNotifications: () => dispatch(getNotifications()),
updateNotificationsSeen: () => dispatch(updateNotificationsSeen()),
deleteNotificationById: (id) => dispatch(deleteNotificationById(id)),
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(ToolBar);
|
src/svg-icons/hardware/device-hub.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareDeviceHub = (props) => (
<SvgIcon {...props}>
<path d="M17 16l-4-4V8.82C14.16 8.4 15 7.3 15 6c0-1.66-1.34-3-3-3S9 4.34 9 6c0 1.3.84 2.4 2 2.82V12l-4 4H3v5h5v-3.05l4-4.2 4 4.2V21h5v-5h-4z"/>
</SvgIcon>
);
HardwareDeviceHub = pure(HardwareDeviceHub);
HardwareDeviceHub.displayName = 'HardwareDeviceHub';
HardwareDeviceHub.muiName = 'SvgIcon';
export default HardwareDeviceHub;
|
src/svg-icons/hardware/tablet.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareTablet = (props) => (
<SvgIcon {...props}>
<path d="M21 4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h18c1.1 0 1.99-.9 1.99-2L23 6c0-1.1-.9-2-2-2zm-2 14H5V6h14v12z"/>
</SvgIcon>
);
HardwareTablet = pure(HardwareTablet);
HardwareTablet.displayName = 'HardwareTablet';
HardwareTablet.muiName = 'SvgIcon';
export default HardwareTablet;
|
modules/withRouter.js | nvartolomei/react-router | import React from 'react'
import hoistStatics from 'hoist-non-react-statics'
import { routerShape } from './PropTypes'
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}
export default function withRouter(WrappedComponent) {
const WithRouter = React.createClass({
contextTypes: { router: routerShape },
render() {
return <WrappedComponent {...this.props} router={this.context.router} />
}
})
WithRouter.displayName = `withRouter(${getDisplayName(WrappedComponent)})`
WithRouter.WrappedComponent = WrappedComponent
return hoistStatics(WithRouter, WrappedComponent)
}
|
ajax/libs/react-instantsearch/4.0.0-beta.0/Dom.js | jdh8/cdnjs | /*! ReactInstantSearch 4.0.0-beta.0 | © Algolia, inc. | https://community.algolia.com/instantsearch.js/react/ */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["Dom"] = factory(require("react"), require("react-dom"));
else
root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Dom"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_0__, __WEBPACK_EXTERNAL_MODULE_425__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 428);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_0__;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEqual2 = __webpack_require__(102);
var _isEqual3 = _interopRequireDefault(_isEqual2);
var _has2 = __webpack_require__(37);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.default = createConnector;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(56);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* @typedef {object} ConnectorDescription
* @property {string} displayName - the displayName used by the wrapper
* @property {function} refine - a function to filter the local state
* @property {function} getSearchParameters - function transforming the local state to a SearchParameters
* @property {function} getMetadata - metadata of the widget
* @property {function} transitionState - hook after the state has changed
* @property {function} getProvidedProps - transform the state into props passed to the wrapped component.
* Receives (props, widgetStates, searchState, metadata) and returns the local state.
* @property {function} getId - Receives props and return the id that will be used to identify the widget
* @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state.
* @property {object} propTypes - PropTypes forwarded to the wrapped component.
* @property {object} defaultProps - default values for the props
*/
/**
* Connectors are the HOC used to transform React components
* into InstantSearch widgets.
* In order to simplify the construction of such connectors
* `createConnector` takes a description and transform it into
* a connector.
* @param {ConnectorDescription} connectorDesc the description of the connector
* @return {Connector} a function that wraps a component into
* an instantsearch connected one.
*/
function createConnector(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var hasRefine = (0, _has3.default)(connectorDesc, 'refine');
var hasSearchForFacetValues = (0, _has3.default)(connectorDesc, 'searchForFacetValues');
var hasSearchParameters = (0, _has3.default)(connectorDesc, 'getSearchParameters');
var hasMetadata = (0, _has3.default)(connectorDesc, 'getMetadata');
var hasTransitionState = (0, _has3.default)(connectorDesc, 'transitionState');
var hasCleanUp = (0, _has3.default)(connectorDesc, 'cleanUp');
var isWidget = hasSearchParameters || hasMetadata || hasTransitionState;
return function (Composed) {
var _class, _temp, _initialiseProps;
return _temp = _class = function (_Component) {
_inherits(Connector, _Component);
function Connector(props, context) {
_classCallCheck(this, Connector);
var _this = _possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context));
_initialiseProps.call(_this);
var _context$ais = context.ais;
var store = _context$ais.store;
var widgetsManager = _context$ais.widgetsManager;
var multiIndexContext = context.multiIndexContext;
_this.state = {
props: _this.getProvidedProps(props)
};
_this.unsubscribe = store.subscribe(function () {
_this.setState({
props: _this.getProvidedProps(_this.props)
});
});
var getSearchParameters = hasSearchParameters ? function (searchParameters) {
return connectorDesc.getSearchParameters.call(_this, searchParameters, _this.props, store.getState().widgets);
} : null;
var getMetadata = hasMetadata ? function (nextWidgetsState) {
return connectorDesc.getMetadata.call(_this, _this.props, nextWidgetsState);
} : null;
var transitionState = hasTransitionState ? function (prevWidgetsState, nextWidgetsState) {
return connectorDesc.transitionState.call(_this, _this.props, prevWidgetsState, nextWidgetsState);
} : null;
if (isWidget) {
_this.unregisterWidget = widgetsManager.registerWidget({
getSearchParameters: getSearchParameters, getMetadata: getMetadata, transitionState: transitionState, multiIndexContext: multiIndexContext
});
}
return _this;
}
_createClass(Connector, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (!(0, _isEqual3.default)(this.props, nextProps)) {
this.setState({
props: this.getProvidedProps(nextProps)
});
if (isWidget) {
// Since props might have changed, we need to re-run getSearchParameters
// and getMetadata with the new props.
this.context.ais.widgetsManager.update();
if (connectorDesc.transitionState) {
this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets));
}
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.unsubscribe();
if (isWidget) {
this.unregisterWidget();
if (hasCleanUp) {
var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets);
this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), {
widgets: newState
}));
this.context.ais.onInternalStateUpdate((0, _utils.removeEmptyKey)(newState));
}
}
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var propsEqual = (0, _utils.shallowEqual)(this.props, nextProps);
if (this.state.props === null || nextState.props === null) {
if (this.state.props === nextState.props) {
return !propsEqual;
}
return true;
}
return !propsEqual || !(0, _utils.shallowEqual)(this.state.props, nextState.props);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
if (this.state.props === null) {
return null;
}
var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {};
var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues,
searchForFacetValues: function searchForFacetValues(facetName, query) {
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`searchForItems`, this will break in the next major version.');
}
_this2.searchForFacetValues(facetName, query);
} } : {};
return _react2.default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(_react.Component), _class.displayName = connectorDesc.displayName + '(' + (0, _utils.getDisplayName)(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = {
// @TODO: more precise state manager propType
ais: _react.PropTypes.object.isRequired,
multiIndexContext: _react.PropTypes.object
}, _initialiseProps = function _initialiseProps() {
var _this3 = this;
this.getProvidedProps = function (props) {
var store = _this3.context.ais.store;
var _store$getState = store.getState();
var results = _store$getState.results;
var searching = _store$getState.searching;
var error = _store$getState.error;
var widgets = _store$getState.widgets;
var metadata = _store$getState.metadata;
var resultsFacetValues = _store$getState.resultsFacetValues;
var searchState = { results: results, searching: searching, error: error };
return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues);
};
this.refine = function () {
var _connectorDesc$refine;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this3.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.searchForFacetValues = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.createURL = function () {
var _connectorDesc$refine2;
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return _this3.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.cleanUp = function () {
var _connectorDesc$cleanU;
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this3].concat(args));
};
}, _temp;
};
}
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(75);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get2 = __webpack_require__(70);
var _get3 = _interopRequireDefault(_get2);
var _omit2 = __webpack_require__(38);
var _omit3 = _interopRequireDefault(_omit2);
var _has2 = __webpack_require__(37);
var _has3 = _interopRequireDefault(_has2);
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; };
exports.getIndex = getIndex;
exports.hasMultipleIndex = hasMultipleIndex;
exports.refineValue = refineValue;
exports.getCurrentRefinementValue = getCurrentRefinementValue;
exports.cleanUpValue = cleanUpValue;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getIndex(context) {
return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex;
}
function hasMultipleIndex(context) {
return context && context.multiIndexContext;
}
// eslint-disable-next-line max-params
function refineValue(searchState, nextRefinement, context, resetPage, namespace) {
if (hasMultipleIndex(context)) {
return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage);
} else {
return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage);
}
}
function refineMultiIndex(searchState, nextRefinement, context, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
var index = getIndex(context);
var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, nextRefinement, page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndex(searchState, nextRefinement, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, nextRefinement, page);
}
// eslint-disable-next-line max-params
function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) {
var _extends4;
var index = getIndex(context);
var page = resetPage ? { page: 1 } : undefined;
var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], (_extends4 = {}, _defineProperty(_extends4, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), _defineProperty(_extends4, 'page', 1), _extends4)))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends(_defineProperty({}, namespace, nextRefinement), page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page);
}
// eslint-disable-next-line max-params
function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) {
var index = getIndex(context);
var refinements = hasMultipleIndex(context) && (0, _has3.default)(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && (0, _has3.default)(searchState, id);
if (refinements) {
var currentRefinement = hasMultipleIndex(context) ? (0, _get3.default)(searchState.indices[index], id) : (0, _get3.default)(searchState, id);
return refinementsCallback(currentRefinement);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return defaultValue;
}
function cleanUpValue(searchState, context, id) {
var index = getIndex(context);
return hasMultipleIndex(context) ? (0, _omit3.default)(searchState, 'indices.' + index + '.' + id) : (0, _omit3.default)(searchState, '' + id);
}
/***/ }),
/* 5 */
/***/ (function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ }),
/* 6 */
/***/ (function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(14),
getRawTag = __webpack_require__(154),
objectToString = __webpack_require__(181);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(84),
baseKeys = __webpack_require__(73),
isArrayLike = __webpack_require__(10);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(133),
getValue = __webpack_require__(156);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(18),
isLength = __webpack_require__(48);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ }),
/* 11 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
var baseMatches = __webpack_require__(261),
baseMatchesProperty = __webpack_require__(262),
identity = __webpack_require__(23),
isArray = __webpack_require__(1),
property = __webpack_require__(331);
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
module.exports = baseIteratee;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = classNames;
var _classnames = __webpack_require__(414);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var prefix = 'ais';
function classNames(block) {
return function () {
for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) {
elements[_key] = arguments[_key];
}
return {
className: (0, _classnames2.default)(elements.filter(function (element) {
return element !== undefined && element !== false;
}).map(function (element) {
return prefix + '-' + block + '__' + element;
}))
};
};
}
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseIteratee = __webpack_require__(12),
baseMap = __webpack_require__(135),
isArray = __webpack_require__(1);
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, baseIteratee(iteratee, 3));
}
module.exports = map;
/***/ }),
/* 16 */
/***/ (function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
var baseKeys = __webpack_require__(73),
getTag = __webpack_require__(55),
isArguments = __webpack_require__(24),
isArray = __webpack_require__(1),
isArrayLike = __webpack_require__(10),
isBuffer = __webpack_require__(25),
isPrototype = __webpack_require__(36),
isTypedArray = __webpack_require__(35);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(7),
isObject = __webpack_require__(5);
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(23),
overRest = __webpack_require__(182),
setToString = __webpack_require__(98);
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
module.exports = baseRest;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(1),
isKey = __webpack_require__(69),
stringToPath = __webpack_require__(193),
toString = __webpack_require__(72);
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
module.exports = castPath;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(86),
baseAssignValue = __webpack_require__(42);
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
module.exports = copyObject;
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(26);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = toKey;
/***/ }),
/* 23 */
/***/ (function(module, exports) {
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(131),
isObjectLike = __webpack_require__(6);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3),
stubFalse = __webpack_require__(203);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54)(module)))
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(7),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
module.exports = isSymbol;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(166),
listCacheDelete = __webpack_require__(167),
listCacheGet = __webpack_require__(168),
listCacheHas = __webpack_require__(169),
listCacheSet = __webpack_require__(170);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(16);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(163);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ }),
/* 30 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(9);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _has2 = __webpack_require__(37);
var _has3 = _interopRequireDefault(_has2);
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; };
exports.default = translatable;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(56);
var _propTypes = __webpack_require__(399);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function translatable(defaultTranslations) {
return function (Composed) {
function Translatable(props) {
var translations = props.translations;
var otherProps = _objectWithoutProperties(props, ['translations']);
var translate = function translate(key) {
for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
var translation = translations && (0, _has3.default)(translations, key) ? translations[key] : defaultTranslations[key];
if (typeof translation === 'function') {
return translation.apply(undefined, params);
}
return translation;
};
return _react2.default.createElement(Composed, _extends({ translate: translate }, otherProps));
}
Translatable.displayName = 'Translatable(' + (0, _utils.getDisplayName)(Composed) + ')';
Translatable.propTypes = {
translations: (0, _propTypes.withKeysPropType)(Object.keys(defaultTranslations))
};
return Translatable;
};
}
/***/ }),
/* 33 */
/***/ (function(module, exports) {
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
module.exports = replaceHolders;
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(81),
baseEach = __webpack_require__(61),
castFunction = __webpack_require__(140),
isArray = __webpack_require__(1);
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, castFunction(iteratee));
}
module.exports = forEach;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(134),
baseUnary = __webpack_require__(45),
nodeUtil = __webpack_require__(180);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ }),
/* 36 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
var baseHas = __webpack_require__(130),
hasPath = __webpack_require__(94);
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
module.exports = has;
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseClone = __webpack_require__(252),
baseUnset = __webpack_require__(274),
castPath = __webpack_require__(20),
copyObject = __webpack_require__(21),
customOmitClone = __webpack_require__(298),
flatRest = __webpack_require__(152),
getAllKeysIn = __webpack_require__(92);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
module.exports = omit;
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(9),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(171),
mapCacheDelete = __webpack_require__(172),
mapCacheGet = __webpack_require__(173),
mapCacheHas = __webpack_require__(174),
mapCacheSet = __webpack_require__(175);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(27),
stackClear = __webpack_require__(188),
stackDelete = __webpack_require__(189),
stackGet = __webpack_require__(190),
stackHas = __webpack_require__(191),
stackSet = __webpack_require__(192);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(149);
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
module.exports = baseAssignValue;
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
var baseFor = __webpack_require__(129),
keys = __webpack_require__(8);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(127),
baseIsNaN = __webpack_require__(259),
strictIndexOf = __webpack_require__(313);
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
module.exports = baseIndexOf;
/***/ }),
/* 45 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ }),
/* 46 */
/***/ (function(module, exports) {
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = func;
return object.placeholder;
}
module.exports = getHolder;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
var createFind = __webpack_require__(294),
findIndex = __webpack_require__(195);
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
module.exports = find;
/***/ }),
/* 48 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(7),
isArray = __webpack_require__(1),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var stringTag = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
module.exports = isString;
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(84),
baseKeysIn = __webpack_require__(260),
isArrayLike = __webpack_require__(10);
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
module.exports = keysIn;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
var arrayReduce = __webpack_require__(85),
baseEach = __webpack_require__(61),
baseIteratee = __webpack_require__(12),
baseReduce = __webpack_require__(269),
isArray = __webpack_require__(1);
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
module.exports = reduce;
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
var toFinite = __webpack_require__(215);
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
module.exports = toInteger;
/***/ }),
/* 53 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 54 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if(!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(119),
Map = __webpack_require__(39),
Promise = __webpack_require__(122),
Set = __webpack_require__(123),
WeakMap = __webpack_require__(80),
baseGetTag = __webpack_require__(7),
toSource = __webpack_require__(76);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.defer = undefined;
var _isEmpty2 = __webpack_require__(17);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
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; };
exports.shallowEqual = shallowEqual;
exports.isSpecialClick = isSpecialClick;
exports.capitalize = capitalize;
exports.assertFacetDefined = assertFacetDefined;
exports.getDisplayName = getDisplayName;
exports.removeEmptyKey = removeEmptyKey;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
function isSpecialClick(event) {
var isMiddleClick = event.button === 1;
return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
}
function capitalize(key) {
return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1);
}
function assertFacetDefined(searchParameters, searchResults, facet) {
var wasRequested = searchParameters.isConjunctiveFacet(facet) || searchParameters.isDisjunctiveFacet(facet);
var wasReceived = Boolean(searchResults.getFacetByName(facet));
if (searchResults.nbHits > 0 && wasRequested && !wasReceived) {
// eslint-disable-next-line no-console
console.warn('A component requested values for facet "' + facet + '", but no facet ' + 'values were retrieved from the API. This means that you should add ' + ('the attribute "' + facet + '" to the list of attributes for faceting in ') + 'your index settings.');
}
}
function getDisplayName(Component) {
return Component.displayName || Component.name || 'UnknownComponent';
}
var resolved = Promise.resolve();
var defer = exports.defer = function defer(f) {
resolved.then(f);
};
function removeEmptyKey(obj) {
Object.keys(obj).forEach(function (key) {
return obj[key] && _typeof(obj[key]) === 'object' && !(0, _isEmpty3.default)(obj[key]) && removeEmptyKey(obj[key]) || obj[key] === undefined || (0, _isEmpty3.default)(obj[key]) && delete obj[key];
});
return obj;
}
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(40),
setCacheAdd = __webpack_require__(183),
setCacheHas = __webpack_require__(184);
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
/***/ }),
/* 58 */
/***/ (function(module, exports) {
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
module.exports = apply;
/***/ }),
/* 59 */
/***/ (function(module, exports) {
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(5);
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
module.exports = baseCreate;
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(43),
createBaseEach = __webpack_require__(290);
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
module.exports = baseEach;
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(20),
toKey = __webpack_require__(22);
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
module.exports = baseGet;
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(132),
isObjectLike = __webpack_require__(6);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(14),
arrayMap = __webpack_require__(11),
isArray = __webpack_require__(1),
isSymbol = __webpack_require__(26);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = baseToString;
/***/ }),
/* 65 */
/***/ (function(module, exports) {
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
/***/ }),
/* 66 */
/***/ (function(module, exports) {
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = copyArray;
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(60),
isObject = __webpack_require__(5);
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
module.exports = createCtor;
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(82),
stubArray = __webpack_require__(106);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
module.exports = getSymbols;
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(1),
isSymbol = __webpack_require__(26);
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
module.exports = isKey;
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(62);
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
module.exports = get;
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(44),
toInteger = __webpack_require__(52);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
module.exports = indexOf;
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(64);
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
module.exports = toString;
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(36),
nativeKeys = __webpack_require__(179);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(57),
arraySome = __webpack_require__(125),
cacheHas = __webpack_require__(65);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53)))
/***/ }),
/* 76 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(8);
var intersection = __webpack_require__(324);
var forOwn = __webpack_require__(322);
var forEach = __webpack_require__(34);
var filter = __webpack_require__(100);
var map = __webpack_require__(15);
var reduce = __webpack_require__(51);
var omit = __webpack_require__(38);
var indexOf = __webpack_require__(71);
var isNaN = __webpack_require__(214);
var isArray = __webpack_require__(1);
var isEmpty = __webpack_require__(17);
var isEqual = __webpack_require__(102);
var isUndefined = __webpack_require__(200);
var isString = __webpack_require__(49);
var isFunction = __webpack_require__(18);
var find = __webpack_require__(47);
var trim = __webpack_require__(204);
var defaults = __webpack_require__(99);
var merge = __webpack_require__(104);
var valToNumber = __webpack_require__(242);
var filterState = __webpack_require__(238);
var RefinementList = __webpack_require__(237);
/**
* like _.find but using _.isEqual to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into
* @param {any} searchedValue the value we're looking for
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find(array, function(currentValue) {
return isEqual(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* Targeted index. This parameter is mandatory.
* @member {string}
*/
this.index = params.index || '';
// Query
/**
* Query string of the instant search. The empty string is a valid query.
* @member {string}
* @see https://www.algolia.com/doc/rest#param-query
*/
this.query = params.query || '';
// Facets
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
// Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* seperated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
/**
* Contains the numeric filters in the raw format of the Algolia API. Setting
* this parameter is not compatible with the usage of numeric filters methods.
* @see https://www.algolia.com/doc/javascript#numericFilters
* @member {string}
*/
this.numericFilters = params.numericFilters;
/**
* Contains the tag filters in the raw format of the Algolia API. Setting this
* parameter is not compatible with the of the add/remove/toggle methods of the
* tag api.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.tagFilters = params.tagFilters;
/**
* Contains the optional tag filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalTagFilters = params.optionalTagFilters;
/**
* Contains the optional facet filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalFacetFilters = params.optionalFacetFilters;
// Misc. parameters
/**
* Number of hits to be returned by the search API
* @member {number}
* @see https://www.algolia.com/doc/rest#param-hitsPerPage
*/
this.hitsPerPage = params.hitsPerPage;
/**
* Number of values for each facetted attribute
* @member {number}
* @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet
*/
this.maxValuesPerFacet = params.maxValuesPerFacet;
/**
* The current page number
* @member {number}
* @see https://www.algolia.com/doc/rest#param-page
*/
this.page = params.page || 0;
/**
* How the query should be treated by the search engine.
* Possible values: prefixAll, prefixLast, prefixNone
* @see https://www.algolia.com/doc/rest#param-queryType
* @member {string}
*/
this.queryType = params.queryType;
/**
* How the typo tolerance behave in the search engine.
* Possible values: true, false, min, strict
* @see https://www.algolia.com/doc/rest#param-typoTolerance
* @member {string}
*/
this.typoTolerance = params.typoTolerance;
/**
* Number of characters to wait before doing one character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo
* @member {number}
*/
this.minWordSizefor1Typo = params.minWordSizefor1Typo;
/**
* Number of characters to wait before doing a second character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos
* @member {number}
*/
this.minWordSizefor2Typos = params.minWordSizefor2Typos;
/**
* Configure the precision of the proximity ranking criterion
* @see https://www.algolia.com/doc/rest#param-minProximity
*/
this.minProximity = params.minProximity;
/**
* Should the engine allow typos on numerics.
* @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens
* @member {boolean}
*/
this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens;
/**
* Should the plurals be ignored
* @see https://www.algolia.com/doc/rest#param-ignorePlurals
* @member {boolean}
*/
this.ignorePlurals = params.ignorePlurals;
/**
* Restrict which attribute is searched.
* @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes
* @member {string}
*/
this.restrictSearchableAttributes = params.restrictSearchableAttributes;
/**
* Enable the advanced syntax.
* @see https://www.algolia.com/doc/rest#param-advancedSyntax
* @member {boolean}
*/
this.advancedSyntax = params.advancedSyntax;
/**
* Enable the analytics
* @see https://www.algolia.com/doc/rest#param-analytics
* @member {boolean}
*/
this.analytics = params.analytics;
/**
* Tag of the query in the analytics.
* @see https://www.algolia.com/doc/rest#param-analyticsTags
* @member {string}
*/
this.analyticsTags = params.analyticsTags;
/**
* Enable the synonyms
* @see https://www.algolia.com/doc/rest#param-synonyms
* @member {boolean}
*/
this.synonyms = params.synonyms;
/**
* Should the engine replace the synonyms in the highlighted results.
* @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight
* @member {boolean}
*/
this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight;
/**
* Add some optional words to those defined in the dashboard
* @see https://www.algolia.com/doc/rest#param-optionalWords
* @member {string}
*/
this.optionalWords = params.optionalWords;
/**
* Possible values are "lastWords" "firstWords" "allOptional" "none" (default)
* @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults
* @member {string}
*/
this.removeWordsIfNoResults = params.removeWordsIfNoResults;
/**
* List of attributes to retrieve
* @see https://www.algolia.com/doc/rest#param-attributesToRetrieve
* @member {string}
*/
this.attributesToRetrieve = params.attributesToRetrieve;
/**
* List of attributes to highlight
* @see https://www.algolia.com/doc/rest#param-attributesToHighlight
* @member {string}
*/
this.attributesToHighlight = params.attributesToHighlight;
/**
* Code to be embedded on the left part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPreTag
* @member {string}
*/
this.highlightPreTag = params.highlightPreTag;
/**
* Code to be embedded on the right part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPostTag
* @member {string}
*/
this.highlightPostTag = params.highlightPostTag;
/**
* List of attributes to snippet
* @see https://www.algolia.com/doc/rest#param-attributesToSnippet
* @member {string}
*/
this.attributesToSnippet = params.attributesToSnippet;
/**
* Enable the ranking informations in the response, set to 1 to activate
* @see https://www.algolia.com/doc/rest#param-getRankingInfo
* @member {number}
*/
this.getRankingInfo = params.getRankingInfo;
/**
* Remove duplicates based on the index setting attributeForDistinct
* @see https://www.algolia.com/doc/rest#param-distinct
* @member {boolean|number}
*/
this.distinct = params.distinct;
/**
* Center of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundLatLng
* @member {string}
*/
this.aroundLatLng = params.aroundLatLng;
/**
* Center of the search, retrieve from the user IP.
* @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP
* @member {boolean}
*/
this.aroundLatLngViaIP = params.aroundLatLngViaIP;
/**
* Radius of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundRadius
* @member {number}
*/
this.aroundRadius = params.aroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundPrecision
* @member {number}
*/
this.minimumAroundRadius = params.minimumAroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-minimumAroundRadius
* @member {number}
*/
this.aroundPrecision = params.aroundPrecision;
/**
* Geo search inside a box.
* @see https://www.algolia.com/doc/rest#param-insideBoundingBox
* @member {string}
*/
this.insideBoundingBox = params.insideBoundingBox;
/**
* Geo search inside a polygon.
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.insidePolygon = params.insidePolygon;
/**
* Allows to specify an ellipsis character for the snippet when we truncate the text
* (added before and after if truncated).
* The default value is an empty string and we recommend to set it to "…"
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.snippetEllipsisText = params.snippetEllipsisText;
/**
* Allows to specify some attributes name on which exact won't be applied.
* Attributes are separated with a comma (for example "name,address" ), you can also use a
* JSON string array encoding (for example encodeURIComponent('["name","address"]') ).
* By default the list is empty.
* @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes
* @member {string|string[]}
*/
this.disableExactOnAttributes = params.disableExactOnAttributes;
/**
* Applies 'exact' on single word queries if the word contains at least 3 characters
* and is not a stop word.
* Can take two values: true or false.
* By default, its set to false.
* @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery
* @member {boolean}
*/
this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery;
// Undocumented parameters, still needed otherwise we fail
this.offset = params.offset;
this.length = params.length;
var self = this;
forOwn(params, function checkForUnknownParameter(paramValue, paramName) {
if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) {
self[paramName] = paramValue;
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = keys(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function(partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = [
'aroundPrecision',
'aroundRadius',
'getRankingInfo',
'minWordSizefor2Typos',
'minWordSizefor1Typo',
'page',
'maxValuesPerFacet',
'distinct',
'minimumAroundRadius',
'hitsPerPage',
'minProximity'
];
forEach(numberKeys, function(k) {
var value = partialState[k];
if (isString(value)) {
var parsedValue = parseFloat(value);
numbers[k] = isNaN(parsedValue) ? value : parsedValue;
}
});
if (partialState.numericRefinements) {
var numericRefinements = {};
forEach(partialState.numericRefinements, function(operators, attribute) {
numericRefinements[attribute] = {};
forEach(operators, function(values, operator) {
var parsedValues = map(values, function(v) {
if (isArray(v)) {
return map(v, function(vPrime) {
if (isString(vPrime)) {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (isString(v)) {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
forEach(newParameters.hierarchicalFacets, function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
}
// get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error(
'[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' +
'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error(
'[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' +
'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (currentState.numericFilters && params.numericRefinements && !isEmpty(params.numericRefinements)) {
return new Error(
"[Numeric filters] Can't switch from the advanced to the managed API. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
if (!isEmpty(currentState.numericRefinements) && params.numericFilters) {
return new Error(
"[Numeric filters] Can't switch from the managed API to the advanced. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optionnal string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var clear = RefinementList.clearRefinement;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'),
facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'),
disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'),
hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet')
});
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) facetting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive facetting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive facetting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function(attribute, operator, v) {
var value = valToNumber(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge({}, this.numericRefinements);
mod[attribute] = merge({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getConjunctiveRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsRefinements[facetName] || [];
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getDisjunctiveRefinements: function(facetName) {
if (!this.isDisjunctiveFacet(facetName)) {
throw new Error(
facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration'
);
}
return this.disjunctiveFacetsRefinements[facetName] || [];
},
/**
* Get the list of hierarchical refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getHierarchicalRefinement: function(facetName) {
// we send an array but we currently do not support multiple
// hierarchicalRefinements for a hierarchicalFacet
return this.hierarchicalFacetsRefinements[facetName] || [];
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getExcludeRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsExcludes[facetName] || [];
},
/**
* Remove all the numeric filter for a given (attribute, operator)
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} [number] the value to be removed
* @return {SearchParameters}
*/
removeNumericRefinement: function(attribute, operator, paramValue) {
if (paramValue !== undefined) {
var paramValueAsNumber = valToNumber(paramValue);
if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator && isEqual(value.val, paramValueAsNumber);
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optionnal string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(this.numericRefinements, attribute);
} else if (isFunction(attribute)) {
return reduce(this.numericRefinements, function(memo, operators, key) {
var operatorList = {};
forEach(operators, function(values, operator) {
var outValues = [];
forEach(values, function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (!isEmpty(outValues)) operatorList[operator] = outValues;
});
if (!isEmpty(operatorList)) memo[key] = operatorList;
return memo;
}, {});
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error(
'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the facetting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Exclude a value from a "normal" facet
* @method
* @param {string} facet attribute to apply the exclusion on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Adds a refinement on a disjunctive facet.
* @method
* @param {string} facet attribute to apply the facetting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.addRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.concat(tag)
};
return this.setQueryParameters(modification);
},
/**
* Remove a facet from the facets attribute of the helper configuration, if it
* is present.
* @method
* @param {string} facet facet name to remove
* @return {SearchParameters}
*/
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
facets: filter(this.facets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: filter(this.disjunctiveFacets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: filter(this.hierarchicalFacets, function(f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the facetted attribute.
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} [value] value used to filter
* @return {SearchParameters}
*/
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Remove a negative refinement on a facet
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Remove a refinement on a disjunctive facet
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.removeRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Remove a tag from the list of tag refinements
* @method
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; })
};
return this.setQueryParameters(modification);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
* @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement}
*/
toggleRefinement: function toggleRefinement(facet, value) {
return this.toggleFacetRefinement(facet, value);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
*/
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) {
return this.toggleHierarchicalFacetRefinement(facet, value);
} else if (this.isConjunctiveFacet(facet)) {
return this.toggleConjunctiveFacetRefinement(facet, value);
} else if (this.isDisjunctiveFacet(facet)) {
return this.toggleDisjunctiveFacetRefinement(facet, value);
}
throw new Error('Cannot refine the undeclared facet ' + facet +
'; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.toggleRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined &&
this.hierarchicalFacetsRefinements[facet].length > 0 && (
// remove current refinement:
// refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0] === value ||
// remove a parent refinement of the current refinement:
// - refinement was 'beer > IPA > Flying dog'
// - call is toggleRefine('beer > IPA')
// - refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0
);
if (upOneOrMultipleLevel) {
if (value.indexOf(separator) === -1) {
// go back to root level
mod[facet] = [];
} else {
mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
}
} else {
mod[facet] = [value];
}
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is not refined.');
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function(facet) {
return indexOf(this.disjunctiveFacets, facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function(facet) {
return indexOf(this.facets, facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value, optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
/**
* Returns true if the facet contains exclusions or if a specific value is
* excluded.
*
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} [value] optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value optionnal, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value optionnal, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return indexOf(refinements, value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (isUndefined(value) && isUndefined(operator)) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined = this.numericRefinements[attribute] &&
!isUndefined(this.numericRefinements[attribute][operator]);
if (isUndefined(value) || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber(value);
var isAttributeValueDefined = !isUndefined(
findArray(this.numericRefinements[attribute][operator], parsedValue)
);
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return indexOf(this.tagRefinements, tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection(
keys(this.numericRefinements),
this.disjunctiveFacets
);
return keys(this.disjunctiveFacetsRefinements)
.concat(disjunctiveNumericRefinedFacets)
.concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
return intersection(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
map(this.hierarchicalFacets, 'name'),
keys(this.hierarchicalFacetsRefinements)
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return filter(this.disjunctiveFacets, function(f) {
return indexOf(refinedFacets, f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
forOwn(this, function(paramValue, paramName) {
if (indexOf(managedParameters, paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user retrieve any parameter value from the SearchParameters
* @param {string} paramName name of the parameter
* @return {any} the value of the parameter
*/
getQueryParameter: function getQueryParameter(paramName) {
if (!this.hasOwnProperty(paramName)) {
throw new Error(
"Parameter '" + paramName + "' is not an attribute of SearchParameters " +
'(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)');
}
return this[paramName];
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var parsedParams = SearchParameters._parseNumbers(params);
return this.mutateMe(function mergeWith(newInstance) {
var ks = keys(params);
forEach(ks, function(k) {
newInstance[k] = parsedParams[k];
});
return newInstance;
});
},
/**
* Returns an object with only the selected attributes.
* @param {string[]} filters filters to retrieve only a subset of the state. It
* accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage)
* or attributes of the index with the notation 'attribute:nameOfMyAttribute'
* @return {object}
*/
filter: function(filters) {
return filterState(this, filters);
},
/**
* Helper function to make it easier to build new instances from a mutating
* function
* @private
* @param {function} fn newMutableState -> previousState -> () function that will
* change the value of the newMutable to the desired state
* @return {SearchParameters} a new instance with the specified modifications applied
*/
mutateMe: function mutateMe(fn) {
var newState = new this.constructor(this);
fn(newState, this);
return newState;
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find(
this.hierarchicalFacets,
{name: hierarchicalFacetName}
);
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
throw new Error(
'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return map(path, trim);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
module.exports = SearchParameters;
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(60),
baseLodash = __webpack_require__(88);
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
module.exports = LazyWrapper;
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(9),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ }),
/* 81 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
/***/ }),
/* 82 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = arrayFilter;
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(44);
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
module.exports = arrayIncludes;
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(139),
isArguments = __webpack_require__(24),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(25),
isIndex = __webpack_require__(30),
isTypedArray = __webpack_require__(35);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ }),
/* 85 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
module.exports = arrayReduce;
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(42),
eq = __webpack_require__(16);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignValue;
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(59),
isArray = __webpack_require__(1);
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
module.exports = baseGetAllKeys;
/***/ }),
/* 88 */
/***/ (function(module, exports) {
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
module.exports = baseLodash;
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
var Uint8Array = __webpack_require__(79);
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
module.exports = cloneArrayBuffer;
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(137),
createBind = __webpack_require__(292),
createCurry = __webpack_require__(293),
createHybrid = __webpack_require__(147),
createPartial = __webpack_require__(296),
getData = __webpack_require__(153),
mergeData = __webpack_require__(308),
setData = __webpack_require__(185),
setWrapToString = __webpack_require__(186),
toInteger = __webpack_require__(52);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
module.exports = createWrap;
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(87),
getSymbols = __webpack_require__(68),
keys = __webpack_require__(8);
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
module.exports = getAllKeys;
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(87),
getSymbolsIn = __webpack_require__(155),
keysIn = __webpack_require__(50);
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
module.exports = getAllKeysIn;
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(96);
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(20),
isArguments = __webpack_require__(24),
isArray = __webpack_require__(1),
isIndex = __webpack_require__(30),
isLength = __webpack_require__(48),
toKey = __webpack_require__(22);
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
module.exports = hasPath;
/***/ }),
/* 95 */
/***/ (function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ }),
/* 96 */
/***/ (function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ }),
/* 97 */
/***/ (function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetToString = __webpack_require__(271),
shortOut = __webpack_require__(187);
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
module.exports = setToString;
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(58),
assignInWith = __webpack_require__(318),
baseRest = __webpack_require__(19),
customDefaultsAssignIn = __webpack_require__(297);
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(args) {
args.push(undefined, customDefaultsAssignIn);
return apply(assignInWith, undefined, args);
});
module.exports = defaults;
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(82),
baseFilter = __webpack_require__(254),
baseIteratee = __webpack_require__(12),
isArray = __webpack_require__(1);
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, baseIteratee(predicate, 3));
}
module.exports = filter;
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(10),
isObjectLike = __webpack_require__(6);
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
module.exports = isArrayLikeObject;
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(63);
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(7),
getPrototype = __webpack_require__(93),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
module.exports = isPlainObject;
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(263),
createAssigner = __webpack_require__(146);
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
module.exports = merge;
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
var baseOrderBy = __webpack_require__(265),
isArray = __webpack_require__(1);
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
module.exports = orderBy;
/***/ }),
/* 106 */
/***/ (function(module, exports) {
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
module.exports = stubArray;
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
exports.arrayToObject = function (source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
target[source] = true;
} else {
return [target, source];
}
return target;
}
if (typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
if (target[i] && typeof target[i] === 'object') {
target[i] = exports.merge(target[i], item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5A) || // a-z
(c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function (obj, references) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && typeof obj[i] === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
keys.forEach(function (key) {
obj[key] = exports.compact(obj[key], refs);
});
return obj;
};
exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
/***/ }),
/* 108 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(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;
runClearTimeout(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) {
runTimeout(drainQueue);
}
};
// 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; };
/***/ }),
/* 109 */
/***/ (function(module, exports) {
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
var basePick = __webpack_require__(266),
flatRest = __webpack_require__(152);
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
module.exports = pick;
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(0);
var _indexUtils = __webpack_require__(4);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* connectRange connector provides the logic to create connected
* components that will give the ability for a user to refine results using
* a numeric range.
* @name connectRange
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - Name of the attribute for faceting
* @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
*/
function getId(props) {
return props.attributeName;
}
var namespace = 'range';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), {}, function (currentRefinement) {
var min = currentRefinement.min;
var max = currentRefinement.max;
if (typeof min === 'string') {
min = parseInt(min, 10);
}
if (typeof max === 'string') {
max = parseInt(max, 10);
}
return { min: min, max: max };
});
}
function _refine(props, searchState, nextRefinement, context) {
if (!isFinite(nextRefinement.min) || !isFinite(nextRefinement.max)) {
throw new Error('You can\'t provide non finite values to the range connector');
}
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaRange',
propTypes: {
id: _react.PropTypes.string,
attributeName: _react.PropTypes.string.isRequired,
defaultRefinement: _react.PropTypes.shape({
min: _react.PropTypes.number.isRequired,
max: _react.PropTypes.number.isRequired
}),
min: _react.PropTypes.number,
max: _react.PropTypes.number
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var min = props.min;
var max = props.max;
var hasMin = typeof min !== 'undefined';
var hasMax = typeof max !== 'undefined';
var index = (0, _indexUtils.getIndex)(this.context);
if (!hasMin || !hasMax) {
if (!searchResults.results || !searchResults.results[index]) {
return {
canRefine: false
};
}
var stats = searchResults.results[index].getFacetByName(attributeName) ? searchResults.results[index].getFacetStats(attributeName) : null;
if (!stats) {
return {
canRefine: false
};
}
if (!hasMin) {
min = stats.min;
}
if (!hasMax) {
max = stats.max;
}
}
var count = searchResults.results && searchResults.results[index] ? searchResults.results[index].getFacetValues(attributeName).map(function (v) {
return {
value: v.name,
count: v.count
};
}) : [];
var _getCurrentRefinement = getCurrentRefinement(props, searchState, this.context);
var _getCurrentRefinement2 = _getCurrentRefinement.min;
var valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2;
var _getCurrentRefinement3 = _getCurrentRefinement.max;
var valueMax = _getCurrentRefinement3 === undefined ? max : _getCurrentRefinement3;
return {
min: min,
max: max,
currentRefinement: { min: valueMin, max: valueMax },
count: count,
canRefine: count.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
params = params.addDisjunctiveFacet(attributeName);
var min = currentRefinement.min;
var max = currentRefinement.max;
if (typeof min !== 'undefined') {
params = params.addNumericRefinement(attributeName, '>=', min);
}
if (typeof max !== 'undefined') {
params = params.addNumericRefinement(attributeName, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var item = void 0;
var hasMin = typeof currentRefinement.min !== 'undefined';
var hasMax = typeof currentRefinement.max !== 'undefined';
if (hasMin || hasMax) {
var itemLabel = '';
if (hasMin) {
itemLabel += currentRefinement.min + ' <= ';
}
itemLabel += props.attributeName;
if (hasMax) {
itemLabel += ' <= ' + currentRefinement.max;
}
item = {
label: itemLabel,
currentRefinement: currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _cleanUp(props, nextState, _this.context);
}
};
}
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: item ? [item] : []
};
}
});
/***/ }),
/* 112 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
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;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
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];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
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;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
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]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + 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) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
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 = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
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');
// For some reason typeof null is "object", so special case here.
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];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = __webpack_require__(235);
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'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(234);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
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);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53), __webpack_require__(108)))
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(34);
var compact = __webpack_require__(320);
var indexOf = __webpack_require__(71);
var findIndex = __webpack_require__(195);
var get = __webpack_require__(70);
var sumBy = __webpack_require__(333);
var find = __webpack_require__(47);
var includes = __webpack_require__(323);
var map = __webpack_require__(15);
var orderBy = __webpack_require__(105);
var defaults = __webpack_require__(99);
var merge = __webpack_require__(104);
var isArray = __webpack_require__(1);
var isFunction = __webpack_require__(18);
var partial = __webpack_require__(328);
var partialRight = __webpack_require__(329);
var formatSort = __webpack_require__(115);
var generateHierarchicalTree = __webpack_require__(240);
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the facetting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objets matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} value the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric fitlers.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
function getIndices(obj) {
var indices = {};
forEach(obj, function(val, idx) { indices[val] = idx; });
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find(
hierarchicalFacets,
function facetKeyMatchesAttribute(hierarchicalFacet) {
return includes(hierarchicalFacet.attributes, hierarchicalAttributeName);
}
);
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, results) {
var mainSubResponse = results[0];
this._rawResults = results;
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = sumBy(results, 'processingTimeMS');
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @member {boolean}
*/
this.timeoutCounts = mainSubResponse.timeoutCounts;
/**
* Boolean that indicates if the computation of the hits did time out.
* @member {boolean}
*/
this.timeoutHits = mainSubResponse.timeoutHits;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = map(state.hierarchicalFacets, function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this;
// Since we send request only for disjunctive facets that have been refined,
// we get the facets informations from the first, general, response.
forEach(mainSubResponse.facets, function(facetValueObject, facetKey) {
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(
state.hierarchicalFacets,
facetKey
);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = indexOf(state.disjunctiveFacets, facetKey) !== -1;
var isFacetConjunctive = indexOf(state.facets, facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
// Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact(this.hierarchicalFacets);
// aggregate the refined disjunctive facets
forEach(disjunctiveFacets, function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
forEach(result.facets, function(facetResults, dfacet) {
var position;
if (hierarchicalFacet) {
position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge(
{},
self.hierarchicalFacets[position][attributeIndex].data,
facetResults
);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaults({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
indexOf(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = results[nextDisjunctiveResult];
forEach(result.facets, function(facetResults, dfacet) {
var position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
// when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaults(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
forEach(state.facetsExcludes, function(excludes, facetName) {
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
forEach(excludes, function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
this.hierarchicalFacets = map(this.hierarchicalFacets, generateHierarchicalTree(state));
this.facets = compact(this.facets);
this.disjunctiveFacets = compact(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the attribute facetted
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
var predicate = {name: name};
return find(this.facets, predicate) ||
find(this.disjunctiveFacets, predicate) ||
find(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the facetted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
var predicate = {name: attribute};
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find(results.facets, predicate);
if (!facet) return [];
return map(facet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isFacetRefined(attribute, k),
isExcluded: results._state.isExcludeRefined(attribute, k)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return map(disjunctiveFacet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = map(node.data, partial(recSort, sortFn));
var sortedChildren = sortFn(children);
var newNode = merge({}, node, {data: sortedChildren});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('results', function(content){
* //get values ordered only by name ascending using the string predicate
* content.getFacetValues('city', {sortBy: ['name:asc']);
* //get values ordered only by count ascending using a function
* content.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.');
var options = defaults({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (isArray(facetValues)) {
return orderBy(facetValues, order[0], order[1]);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partialRight(orderBy, order[0], order[1]), facetValues);
} else if (isFunction(options.sortBy)) {
if (isArray(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partial(vanillaSortFn, options.sortBy), facetValues);
}
throw new Error(
'options.sortBy is optional but if defined it must be ' +
'either an array of string (predicates) or a sorting function'
);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the facetted attribute
* @return {object} The stats of the facet
*/
SearchResults.prototype.getFacetStats = function(attribute) {
if (this._state.isConjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.facets, attribute);
} else if (this._state.isDisjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
}
throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`');
};
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find(facetList, {name: facetName});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhausistivity for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
forEach(state.facetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
forEach(state.facetsExcludes, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
forEach(state.disjunctiveFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
forEach(state.hierarchicalFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
forEach(state.numericRefinements, function(operators, attributeName) {
forEach(operators, function(values, operator) {
forEach(values, function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
forEach(state.tagRefinements, function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var count = get(facet, 'data[' + name + ']');
var exhaustive = get(facet, 'exhaustive');
return {
type: type,
attributeName: attributeName,
name: name,
count: count || 0,
exhaustive: exhaustive || false
};
}
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var splitted = name.split(facetDeclaration.separator);
var configuredName = splitted[splitted.length - 1];
for (var i = 0; facet !== undefined && i < splitted.length; ++i) {
facet = find(facet.data, {name: splitted[i]});
}
var count = get(facet, 'count');
var exhaustive = get(facet, 'exhaustive');
return {
type: 'hierarchical',
attributeName: attributeName,
name: configuredName,
count: count || 0,
exhaustive: exhaustive || false
};
}
module.exports = SearchResults;
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var reduce = __webpack_require__(51);
var find = __webpack_require__(47);
var startsWith = __webpack_require__(332);
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
module.exports = function formatSort(sortBy, defaults) {
return reduce(sortBy, function preparePredicate(out, sortInstruction) {
var sortInstructions = sortInstruction.split(':');
if (defaults && sortInstructions.length === 1) {
var similarDefault = find(defaults, function(predicate) {
return startsWith(predicate, sortInstruction[0]);
});
if (similarDefault) {
sortInstructions = similarDefault.split(':');
}
}
out[0].push(sortInstructions[0]);
out[1].push(sortInstructions[1]);
return out;
}, [[], []]);
};
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Module containing the functions to serialize and deserialize
* {SearchParameters} in the query string format
* @module algoliasearchHelper.url
*/
var shortener = __webpack_require__(239);
var SearchParameters = __webpack_require__(77);
var qs = __webpack_require__(338);
var bind = __webpack_require__(319);
var forEach = __webpack_require__(34);
var pick = __webpack_require__(110);
var map = __webpack_require__(15);
var mapKeys = __webpack_require__(325);
var mapValues = __webpack_require__(326);
var isString = __webpack_require__(49);
var isPlainObject = __webpack_require__(103);
var isArray = __webpack_require__(1);
var invert = __webpack_require__(198);
var encode = __webpack_require__(107).encode;
function recursiveEncode(input) {
if (isPlainObject(input)) {
return mapValues(input, recursiveEncode);
}
if (isArray(input)) {
return map(input, recursiveEncode);
}
if (isString(input)) {
return encode(input);
}
return input;
}
var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR'];
var stateKeys = shortener.ENCODED_PARAMETERS;
function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) {
if (prefixRegexp !== null) {
a = a.replace(prefixRegexp, '');
b = b.replace(prefixRegexp, '');
}
a = invertedMapping[a] || a;
b = invertedMapping[b] || b;
if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) {
if (a === 'q') return -1;
if (b === 'q') return 1;
var isARefinements = refinementsParameters.indexOf(a) !== -1;
var isBRefinements = refinementsParameters.indexOf(b) !== -1;
if (isARefinements && !isBRefinements) {
return 1;
} else if (isBRefinements && !isARefinements) {
return -1;
}
}
return a.localeCompare(b);
}
/**
* Read a query string and return an object containing the state
* @param {string} queryString the query string that will be decoded
* @param {object} [options] accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
*/
exports.getStateFromQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var partialStateWithPrefix = qs.parse(queryString);
var prefixRegexp = new RegExp('^' + prefixForParameters);
var partialState = mapKeys(
partialStateWithPrefix,
function(v, k) {
var hasPrefix = prefixForParameters && prefixRegexp.test(k);
var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k;
var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey);
return decodedKey || unprefixedKey;
}
);
var partialStateWithParsedNumbers = SearchParameters._parseNumbers(partialState);
return pick(partialStateWithParsedNumbers, SearchParameters.PARAMETERS);
};
/**
* Retrieve an object of all the properties that are not understandable as helper
* parameters.
* @param {string} queryString the query string to read
* @param {object} [options] the options
* - prefixForParameters : prefix used for the helper configuration keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
exports.getUnrecognizedParametersInQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix;
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var foreignConfig = {};
var config = qs.parse(queryString);
if (prefixForParameters) {
var prefixRegexp = new RegExp('^' + prefixForParameters);
forEach(config, function(v, key) {
if (!prefixRegexp.test(key)) foreignConfig[key] = v;
});
} else {
forEach(config, function(v, key) {
if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v;
});
}
return foreignConfig;
};
/**
* Generate a query string for the state passed according to the options
* @param {SearchParameters} state state to serialize
* @param {object} [options] May contain the following parameters :
* - prefix : prefix in front of the keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* - moreAttributes : more values to be added in the query string. Those values
* won't be prefixed.
* - safe : get safe urls for use in emails, chat apps or any application auto linking urls.
* All parameters and values will be encoded in a way that it's safe to share them.
* Default to false for legacy reasons ()
* @return {string} the query string
*/
exports.getQueryStringFromState = function(state, options) {
var moreAttributes = options && options.moreAttributes;
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var safe = options && options.safe || false;
var invertedMapping = invert(mapping);
var stateForUrl = safe ? state : recursiveEncode(state);
var encodedState = mapKeys(
stateForUrl,
function(v, k) {
var shortK = shortener.encode(k);
return prefixForParameters + (mapping[shortK] || shortK);
}
);
var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters);
var sort = bind(sortQueryStringValues, null, prefixRegexp, invertedMapping);
if (moreAttributes) {
var stateQs = qs.stringify(encodedState, {encode: safe, sort: sort});
var moreQs = qs.stringify(moreAttributes, {encode: safe});
if (!stateQs) return moreQs;
return stateQs + '&' + moreQs;
}
return qs.stringify(encodedState, {encode: safe, sort: sort});
};
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = '2.19.0';
/***/ }),
/* 118 */
/***/ (function(module, exports) {
module.exports = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(9),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(157),
hashDelete = __webpack_require__(158),
hashGet = __webpack_require__(159),
hashHas = __webpack_require__(160),
hashSet = __webpack_require__(161);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(60),
baseLodash = __webpack_require__(88);
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
module.exports = LodashWrapper;
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(9),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(9),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ }),
/* 124 */
/***/ (function(module, exports) {
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
module.exports = arrayIncludesWith;
/***/ }),
/* 125 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(42),
eq = __webpack_require__(16);
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignMergeValue;
/***/ }),
/* 127 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(59),
isFlattenable = __webpack_require__(306);
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
module.exports = baseFlatten;
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
var createBaseFor = __webpack_require__(291);
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
/***/ }),
/* 130 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
module.exports = baseHas;
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(7),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(41),
equalArrays = __webpack_require__(74),
equalByTag = __webpack_require__(150),
equalObjects = __webpack_require__(151),
getTag = __webpack_require__(55),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(25),
isTypedArray = __webpack_require__(35);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(18),
isMasked = __webpack_require__(164),
isObject = __webpack_require__(5),
toSource = __webpack_require__(76);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(7),
isLength = __webpack_require__(48),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(61),
isArrayLike = __webpack_require__(10);
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
module.exports = baseMap;
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(62),
baseSet = __webpack_require__(270),
castPath = __webpack_require__(20);
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
module.exports = basePickBy;
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(23),
metaMap = __webpack_require__(178);
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
module.exports = baseSetData;
/***/ }),
/* 138 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
/***/ }),
/* 139 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(23);
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
module.exports = castFunction;
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54)(module)))
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(89);
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
module.exports = cloneTypedArray;
/***/ }),
/* 143 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
module.exports = composeArgs;
/***/ }),
/* 144 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
module.exports = composeArgsRight;
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(19),
isIterateeCall = __webpack_require__(213);
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(143),
composeArgsRight = __webpack_require__(144),
countHolders = __webpack_require__(289),
createCtor = __webpack_require__(67),
createRecurry = __webpack_require__(148),
getHolder = __webpack_require__(46),
reorder = __webpack_require__(312),
replaceHolders = __webpack_require__(33),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_ARY_FLAG = 128,
WRAP_FLIP_FLAG = 512;
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
module.exports = createHybrid;
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
var isLaziable = __webpack_require__(307),
setData = __webpack_require__(185),
setWrapToString = __webpack_require__(186);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
module.exports = createRecurry;
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(9);
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
module.exports = defineProperty;
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(14),
Uint8Array = __webpack_require__(79),
eq = __webpack_require__(16),
equalArrays = __webpack_require__(74),
mapToArray = __webpack_require__(95),
setToArray = __webpack_require__(97);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
var getAllKeys = __webpack_require__(91);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
var flatten = __webpack_require__(196),
overRest = __webpack_require__(182),
setToString = __webpack_require__(98);
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
module.exports = flatRest;
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
var metaMap = __webpack_require__(178),
noop = __webpack_require__(327);
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
module.exports = getData;
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(14);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(59),
getPrototype = __webpack_require__(93),
getSymbols = __webpack_require__(68),
stubArray = __webpack_require__(106);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
module.exports = getSymbolsIn;
/***/ }),
/* 156 */
/***/ (function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(31);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ }),
/* 158 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(31);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(31);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(31);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(60),
getPrototype = __webpack_require__(93),
isPrototype = __webpack_require__(36);
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
module.exports = initCloneObject;
/***/ }),
/* 163 */
/***/ (function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(145);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(5);
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
module.exports = isStrictComparable;
/***/ }),
/* 166 */
/***/ (function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(28);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(28);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(28);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(28);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(120),
ListCache = __webpack_require__(27),
Map = __webpack_require__(39);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(29);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(29);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(29);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(29);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ }),
/* 176 */
/***/ (function(module, exports) {
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
module.exports = matchesStrictComparable;
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
var memoize = __webpack_require__(202);
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
module.exports = memoizeCapped;
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
var WeakMap = __webpack_require__(80);
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(96);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(75);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54)(module)))
/***/ }),
/* 181 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(58);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
module.exports = overRest;
/***/ }),
/* 183 */
/***/ (function(module, exports) {
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
/***/ }),
/* 184 */
/***/ (function(module, exports) {
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
/***/ }),
/* 185 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(137),
shortOut = __webpack_require__(187);
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
module.exports = setData;
/***/ }),
/* 186 */
/***/ (function(module, exports, __webpack_require__) {
var getWrapDetails = __webpack_require__(301),
insertWrapDetails = __webpack_require__(305),
setToString = __webpack_require__(98),
updateWrapDetails = __webpack_require__(316);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
module.exports = setWrapToString;
/***/ }),
/* 187 */
/***/ (function(module, exports) {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
module.exports = shortOut;
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(27);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ }),
/* 189 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ }),
/* 190 */
/***/ (function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ }),
/* 191 */
/***/ (function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(27),
Map = __webpack_require__(39),
MapCache = __webpack_require__(40);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {
var memoizeCapped = __webpack_require__(177);
/** Used to match property names within property paths. */
var reLeadingDot = /^\./,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (reLeadingDot.test(string)) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
module.exports = stringToPath;
/***/ }),
/* 194 */
/***/ (function(module, exports) {
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = constant;
/***/ }),
/* 195 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(127),
baseIteratee = __webpack_require__(12),
toInteger = __webpack_require__(52);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index);
}
module.exports = findIndex;
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
var baseFlatten = __webpack_require__(128);
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
module.exports = flatten;
/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {
var baseHasIn = __webpack_require__(255),
hasPath = __webpack_require__(94);
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
module.exports = hasIn;
/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(194),
createInverter = __webpack_require__(295),
identity = __webpack_require__(23);
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
result[value] = key;
}, constant(identity));
module.exports = invert;
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(7),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
module.exports = isNumber;
/***/ }),
/* 200 */
/***/ (function(module, exports) {
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
module.exports = isUndefined;
/***/ }),
/* 201 */
/***/ (function(module, exports) {
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
module.exports = last;
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(40);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
module.exports = memoize;
/***/ }),
/* 203 */
/***/ (function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(64),
castSlice = __webpack_require__(277),
charsEndIndex = __webpack_require__(278),
charsStartIndex = __webpack_require__(279),
stringToArray = __webpack_require__(314),
toString = __webpack_require__(72);
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
module.exports = trim;
/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
module.exports = {
'default': 'RFC3986',
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _react = __webpack_require__(0);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectCurrentRefinements connector provides the logic to build a widget that will
* give the user the ability to remove all or some of the filters that were
* set.
* @name connectCurrentRefinements
* @kind connector
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {function} [clearsQuery=false] - Pass true to also clear the search query
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values.
* @providedPropType {function} query - the search query
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaCurrentRefinements',
propTypes: {
transformItems: _react.PropTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) {
var items = metadata.reduce(function (res, meta) {
if (typeof meta.items !== 'undefined') {
if (!props.clearsQuery && meta.id === 'query') {
return res;
} else {
if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') {
return res;
}
return res.concat(meta.items);
}
}
return res;
}, []);
return {
items: props.transformItems ? props.transformItems(items) : items,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, items) {
// `value` corresponds to our internal clear function computed in each connector metadata.
var refinementsToClear = items instanceof Array ? items.map(function (item) {
return item.value;
}) : [items];
return refinementsToClear.reduce(function (res, clear) {
return clear(res);
}, searchState);
}
});
/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _highlight = __webpack_require__(233);
var _highlight2 = _interopRequireDefault(_highlight);
var _highlightTags = __webpack_require__(209);
var _highlightTags2 = _interopRequireDefault(_highlightTags);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var highlight = function highlight(_ref) {
var attributeName = _ref.attributeName;
var hit = _ref.hit;
var highlightProperty = _ref.highlightProperty;
return (0, _highlight2.default)({
attributeName: attributeName,
hit: hit,
preTag: _highlightTags2.default.highlightPreTag,
postTag: _highlightTags2.default.highlightPostTag,
highlightProperty: highlightProperty
});
};
/**
* connectHighlight connector provides the logic to create an highlighter
* component that will retrieve, parse and render an highlighted attribute
* from an Algolia hit.
* @name connectHighlight
* @kind connector
* @category connector
* @providedPropType {function} highlight - the function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attribute: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute to look for and `hit` which is the hit from Algolia. It returns an array of object `{value: string, isHighlighted: boolean}`.
* @example
* const CustomHighlight = connectHighlight(({highlight, attributeName, hit, highlightProperty) => {
* const parsedHit = highlight({attributeName, hit, highlightProperty});
* return parsedHit.map(part => {
* if(part.isHighlighted) return <em>{part.value}</em>;
* return part.value:
* });
* });
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHighlighter',
propTypes: {},
getProvidedProps: function getProvidedProps() {
return { highlight: highlight };
}
});
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _SearchBox = __webpack_require__(342);
var _SearchBox2 = _interopRequireDefault(_SearchBox);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var itemsPropType = _react.PropTypes.arrayOf(_react.PropTypes.shape({
value: _react.PropTypes.any,
label: _react.PropTypes.string.isRequired,
items: function items() {
return itemsPropType.apply(undefined, arguments);
}
}));
var List = function (_Component) {
_inherits(List, _Component);
function List() {
_classCallCheck(this, List);
var _this = _possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this));
_this.defaultProps = {
isFromSearch: false
};
_this.onShowMoreClick = function () {
_this.setState(function (state) {
return {
extended: !state.extended
};
});
};
_this.getLimit = function () {
var _this$props = _this.props;
var limitMin = _this$props.limitMin;
var limitMax = _this$props.limitMax;
var extended = _this.state.extended;
return extended ? limitMax : limitMin;
};
_this.renderItem = function (item) {
var items = item.items && _react2.default.createElement(
'div',
_this.props.cx('itemItems'),
item.items.slice(0, _this.getLimit()).map(function (child) {
return _this.renderItem(child, item);
})
);
return _react2.default.createElement(
'div',
_extends({
key: item.key || item.label
}, _this.props.cx('item', item.isRefined && 'itemSelected', item.noRefinement && 'itemNoRefinement', items && 'itemParent', items && item.isRefined && 'itemSelectedParent')),
_this.props.renderItem(item),
items
);
};
_this.state = {
extended: false,
query: ''
};
return _this;
}
_createClass(List, [{
key: 'renderShowMore',
value: function renderShowMore() {
var _props = this.props;
var showMore = _props.showMore;
var translate = _props.translate;
var cx = _props.cx;
var extended = this.state.extended;
var disabled = this.props.limitMin >= this.props.items.length;
if (!showMore) {
return null;
}
return _react2.default.createElement(
'button',
_extends({ disabled: disabled
}, cx('showMore', disabled && 'showMoreDisabled'), {
onClick: this.onShowMoreClick
}),
translate('showMore', extended)
);
}
}, {
key: 'renderSearchBox',
value: function renderSearchBox() {
var _this2 = this;
var _props2 = this.props;
var cx = _props2.cx;
var searchForItems = _props2.searchForItems;
var isFromSearch = _props2.isFromSearch;
var translate = _props2.translate;
var items = _props2.items;
var selectItem = _props2.selectItem;
var noResults = items.length === 0 && this.state.query !== '' ? _react2.default.createElement(
'div',
cx('noResults'),
translate('noResults')
) : null;
return _react2.default.createElement(
'div',
cx('SearchBox'),
_react2.default.createElement(_SearchBox2.default, {
currentRefinement: isFromSearch ? this.state.query : '',
refine: function refine(value) {
_this2.setState({ query: value });
searchForItems(value);
},
focusShortcuts: [],
translate: translate,
onSubmit: function onSubmit(e) {
e.preventDefault();
e.stopPropagation();
if (isFromSearch) {
selectItem(items[0]);
}
}
}),
noResults
);
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _props3 = this.props;
var cx = _props3.cx;
var items = _props3.items;
var withSearchBox = _props3.withSearchBox;
var canRefine = _props3.canRefine;
var searchBox = withSearchBox ? this.renderSearchBox() : null;
if (items.length === 0) {
return _react2.default.createElement(
'div',
cx('root', !canRefine && 'noRefinement'),
searchBox
);
}
// Always limit the number of items we show on screen, since the actual
// number of retrieved items might vary with the `maxValuesPerFacet` config
// option.
var limit = this.getLimit();
return _react2.default.createElement(
'div',
cx('root', !this.props.canRefine && 'noRefinement'),
searchBox,
_react2.default.createElement(
'div',
cx('items'),
items.slice(0, limit).map(function (item) {
return _this3.renderItem(item);
})
),
this.renderShowMore()
);
}
}]);
return List;
}(_react.Component);
List.propTypes = {
cx: _react.PropTypes.func.isRequired,
// Only required with showMore.
translate: _react.PropTypes.func,
items: itemsPropType,
renderItem: _react.PropTypes.func.isRequired,
selectItem: _react.PropTypes.func,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
limit: _react.PropTypes.number,
show: _react.PropTypes.func,
searchForItems: _react.PropTypes.func,
withSearchBox: _react.PropTypes.bool,
isFromSearch: _react.PropTypes.bool,
canRefine: _react.PropTypes.bool
};
exports.default = List;
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var timestamp = Date.now().toString();
exports.default = {
highlightPreTag: "<ais-highlight-" + timestamp + ">",
highlightPostTag: "</ais-highlight-" + timestamp + ">"
};
/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var AlgoliaSearchHelper = __webpack_require__(241);
var SearchParameters = __webpack_require__(77);
var SearchResults = __webpack_require__(114);
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(result) {
* console.log(result);
* });
* helper.toggleRefine('Movies & TV Shows')
* .toggleRefine('Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new AlgoliaSearchHelper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = __webpack_require__(117);
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults;
/**
* URL tools to generate query string and parse them from/into
* SearchParameters
* @member module:algoliasearchHelper.url
* @type {object} {@link url}
*
*/
algoliasearchHelper.url = __webpack_require__(116);
module.exports = algoliasearchHelper;
/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
var inherits = __webpack_require__(345);
function AlgoliaSearchError(message, extraProperties) {
var forEach = __webpack_require__(109);
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
module.exports = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = __webpack_require__(415);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
return exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (typeof process !== 'undefined' && 'env' in process) {
return process.env.DEBUG;
}
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(108)))
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(16),
isArrayLike = __webpack_require__(10),
isIndex = __webpack_require__(30),
isObject = __webpack_require__(5);
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
module.exports = isIterateeCall;
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
var isNumber = __webpack_require__(199);
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
module.exports = isNaN;
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
var toNumber = __webpack_require__(334);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
module.exports = toFinite;
/***/ }),
/* 216 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys2 = __webpack_require__(8);
var _keys3 = _interopRequireDefault(_keys2);
var _difference2 = __webpack_require__(321);
var _difference3 = _interopRequireDefault(_difference2);
var _omit2 = __webpack_require__(38);
var _omit3 = _interopRequireDefault(_omit2);
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 _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'configure';
}
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var items = (0, _omit3.default)(props, 'children');
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
var items = (0, _omit3.default)(props, 'children');
var nonPresentKeys = this._props ? (0, _difference3.default)((0, _keys3.default)(this._props), (0, _keys3.default)(props)) : [];
this._props = props;
var nextValue = _defineProperty({}, id, _extends({}, (0, _omit3.default)(nextSearchState[id], nonPresentKeys), items));
return (0, _indexUtils.refineValue)(nextSearchState, nextValue, this.context);
},
cleanUp: function cleanUp(props, searchState) {
var id = getId();
var index = (0, _indexUtils.getIndex)(this.context);
var subState = (0, _indexUtils.hasMultipleIndex)(this.context) && searchState.indices ? searchState.indices[index] : searchState;
var configureKeys = subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = _defineProperty({}, id, configureState);
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context);
}
});
/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getId = undefined;
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _algoliasearchHelper = __webpack_require__(210);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var getId = exports.getId = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue(path, props, searchState, context) {
var id = props.id;
var attributes = props.attributes;
var separator = props.separator;
var rootPath = props.rootPath;
var showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement(props, searchState, context);
var nextRefinement = void 0;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new _algoliasearchHelper.SearchParameters({
hierarchicalFacets: [{
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}]
});
nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0];
}
return nextRefinement;
}
function transformValue(value, limit, props, searchState, context) {
return value.slice(0, limit).map(function (v) {
return {
label: v.name,
value: getValue(v.path, props, searchState, context),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue(v.data, limit, props, searchState, context)
};
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
var sortBy = ['name:asc'];
/**
* connectHierarchicalMenu connector provides the logic to build a widget that will
* give the user the ability to explore a tree-like structure.
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
* @name connectHierarchicalMenu
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax.
* @propType {number} [limitMin=10] - The maximum number of items displayed.
* @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHierarchicalMenu',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
separator: _react.PropTypes.string,
rootPath: _react.PropTypes.string,
showParentLevel: _react.PropTypes.bool,
defaultRefinement: _react.PropTypes.string,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
transformItems: _react.PropTypes.func
},
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore;
var limitMin = props.limitMin;
var limitMax = props.limitMax;
var id = getId(props);
var results = searchResults.results;
var index = (0, _indexUtils.getIndex)(this.context);
var isFacetPresent = Boolean(results) && Boolean(results[index]) && Boolean(results[index].getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: false
};
}
var limit = showMore ? limitMax : limitMin;
var value = results[index].getFacetValues(id, { sortBy: sortBy });
var items = value.data ? transformValue(value.data, limit, props, searchState, this.context) : [];
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributes = props.attributes;
var separator = props.separator;
var rootPath = props.rootPath;
var showParentLevel = props.showParentLevel;
var showMore = props.showMore;
var limitMin = props.limitMin;
var limitMax = props.limitMax;
var id = getId(props);
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var rootAttribute = props.attributes[0];
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: !currentRefinement ? [] : [{
label: rootAttribute + ': ' + currentRefinement,
attributeName: rootAttribute,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 218 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectHits connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
* @name connectHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var index = (0, _indexUtils.getIndex)(this.context);
var hits = searchResults.results && searchResults.results[index] ? searchResults.results[index].hits : [];
return { hits: hits };
},
/* Hits needs to be considered as a widget to trigger a search if no others widgets are used.
* To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState
* See createConnector.js
* */
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'hitsPerPage';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* connectHitsPerPage connector provides the logic to create connected
* components that will allow a user to choose to display more or less results from Algolia.
* @name connectHitsPerPage
* @kind connector
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {{value: number, label: string}[]} items - List of hits per page options.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHitsPerPage',
propTypes: {
defaultRefinement: _react.PropTypes.number.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string,
value: _react.PropTypes.number.isRequired
})).isRequired,
transformItems: _react.PropTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false });
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement(props, searchState, this.context));
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 220 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function getId() {
return 'page';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
var page = 1;
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
currentRefinement = parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* InfiniteHits connector provides the logic to create connected
* components that will render an continuous list of results retrieved from
* Algolia. This connector provides a function to load more results.
* @name connectInfiniteHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {boolean} hasMore - indicates if there are more pages to load
* @providedPropType {function} refine - call to load more results
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var index = (0, _indexUtils.getIndex)(this.context);
if (!searchResults.results || !searchResults.results[index]) {
this._allResults = [];
return {
hits: this._allResults,
hasMore: false
};
}
var _searchResults$result = searchResults.results[index];
var hits = _searchResults$result.hits;
var page = _searchResults$result.page;
var nbPages = _searchResults$result.nbPages;
var hitsPerPage = _searchResults$result.hitsPerPage;
if (page === 0) {
this._allResults = hits;
} else {
var previousPage = this._allResults.length / hitsPerPage - 1;
if (page > previousPage) {
this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hits));
} else if (page < previousPage) {
this._allResults = hits;
}
// If it is the same page we do not touch the page result list
}
var lastPageIndex = nbPages - 1;
var hasMore = page < lastPageIndex;
return {
hits: this._allResults,
hasMore: hasMore
};
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQueryParameters({
page: getCurrentRefinement(props, searchState, this.context) - 1
});
},
refine: function refine(props, searchState) {
var id = getId();
var nextPage = getCurrentRefinement(props, searchState, this.context) + 1;
var nextValue = _defineProperty({}, id, nextPage);
var resetPage = false;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
}
});
/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _orderBy2 = __webpack_require__(105);
var _orderBy3 = _interopRequireDefault(_orderBy2);
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var namespace = 'menu';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement(props, searchState, context);
return name === currentRefinement ? '' : name;
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
var sortBy = ['count:desc', 'name:asc'];
/**
* connectMenu connector provides the logic to build a widget that will
* give the user tha ability to choose a single value for a specific facet.
* @name connectMenu
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of diplayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaMenu',
propTypes: {
attributeName: _react.PropTypes.string.isRequired,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
defaultRefinement: _react.PropTypes.string,
transformItems: _react.PropTypes.func,
withSearchBox: _react.PropTypes.bool,
searchForFacetValues: _react.PropTypes.bool },
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var _this = this;
var results = searchResults.results;
var attributeName = props.attributeName;
var showMore = props.showMore;
var limitMin = props.limitMin;
var limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var index = (0, _indexUtils.getIndex)(this.context);
var canRefine = Boolean(results) && Boolean(results[index]) && Boolean(results[index].getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.');
}
// Search For Facet Values is not available with derived helper (used for multi index search)
if (props.withSearchBox && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: canRefine
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results[index].getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) {
return {
label: v.name,
value: getValue(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var sortedItems = withSearchBox && !isFromSearch ? (0, _orderBy3.default)(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items;
var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName;
var showMore = props.showMore;
var limitMin = props.limitMin;
var limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
searchParameters = searchParameters.addDisjunctiveFacet(attributeName);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this2 = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: currentRefinement === null ? [] : [{
label: props.attributeName + ': ' + currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _refine(props, nextState, '', _this2.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 222 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _has2 = __webpack_require__(37);
var _has3 = _interopRequireDefault(_has2);
var _isEmpty2 = __webpack_require__(17);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _find3 = __webpack_require__(47);
var _find4 = _interopRequireDefault(_find3);
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _react = __webpack_require__(0);
var _indexUtils = __webpack_require__(4);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
return (item.start ? item.start : '') + ':' + (item.end ? item.end : '');
}
function parseItem(value) {
if (value.length === 0) {
return { start: null, end: null };
}
var _value$split = value.split(':');
var _value$split2 = _slicedToArray(_value$split, 2);
var startStr = _value$split2[0];
var endStr = _value$split2[1];
return {
start: startStr.length > 0 ? parseInt(startStr, 10) : null,
end: endStr.length > 0 ? parseInt(endStr, 10) : null
};
}
var namespace = 'multiRange';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), '', function (currentRefinement) {
if (currentRefinement === '') {
return '';
}
return currentRefinement;
});
}
function isRefinementsRangeIncludesInsideItemRange(stats, start, end) {
return stats.min > start && stats.min < end || stats.max > start && stats.max < end;
}
function isItemRangeIncludedInsideRefinementsRange(stats, start, end) {
return start > stats.min && start < stats.max || end > stats.min && end < stats.max;
}
function itemHasRefinement(attributeName, results, value) {
var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
var range = value.split(':');
var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]);
var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]);
return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end)));
}
function _refine(props, searchState, nextRefinement, context) {
var nextValue = _defineProperty({}, getId(props, searchState), nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectMultiRange connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectMultiRange
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaMultiRange',
propTypes: {
id: _react.PropTypes.string,
attributeName: _react.PropTypes.string.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.node,
start: _react.PropTypes.number,
end: _react.PropTypes.number
})).isRequired,
transformItems: _react.PropTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var index = (0, _indexUtils.getIndex)(this.context);
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: searchResults.results && searchResults.results[index] ? itemHasRefinement(getId(props), searchResults.results[index], value) : false
};
});
var stats = (0, _has3.default)(searchResults, 'results.' + index) && searchResults.results[index].getFacetByName(attributeName) ? searchResults.results[index].getFacetStats(attributeName) : null;
var refinedItem = (0, _find4.default)(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: (0, _isEmpty3.default)(refinedItem),
noRefinement: !stats,
label: 'All'
});
}
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement,
canRefine: items.length > 0 && items.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName;
var _parseItem = parseItem(getCurrentRefinement(props, searchState, this.context));
var start = _parseItem.start;
var end = _parseItem.end;
searchParameters = searchParameters.addDisjunctiveFacet(attributeName);
if (start) {
searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start);
}
if (end) {
searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var value = getCurrentRefinement(props, searchState, this.context);
var items = [];
var index = (0, _indexUtils.getIndex)(this.context);
if (value !== '') {
var _find2 = (0, _find4.default)(props.items, function (item) {
return stringifyItem(item) === value;
});
var label = _find2.label;
items.push({
label: props.attributeName + ': ' + label,
attributeName: props.attributeName,
currentRefinement: label,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _indexUtils = __webpack_require__(4);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'page';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
var page = 1;
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
function _refine(props, searchState, nextPage, context) {
var id = getId();
var nextValue = _defineProperty({}, id, nextPage);
var resetPage = false;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage);
}
/**
* connectPagination connector provides the logic to build a widget that will
* let the user displays hits corresponding to a certain page.
* @name connectPagination
* @kind connector
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [pagesPadding=3] - How many page links to display around the current page.
* @propType {number} [maxPages=Infinity] - Maximum number of pages to display.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {number} nbPages - the total of existing pages
* @providedPropType {number} currentRefinement - the page refinement currently applied
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var index = (0, _indexUtils.getIndex)(this.context);
if (!searchResults.results || !searchResults.results[index]) {
return null;
}
var nbPages = searchResults.results[index].nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
return _refine(props, searchState, nextPage, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement(props, searchState, this.context) - 1);
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectPoweredBy connector provides the logic to build a widget that
* will display a link to algolia.
* @name connectPoweredBy
* @kind connector
* @providedPropType {string} url - the url to redirect to algolia
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaPoweredBy',
propTypes: {},
getProvidedProps: function getProvidedProps() {
var url = 'https://www.algolia.com/?' + 'utm_source=instantsearch.js&' + 'utm_medium=website&' + ('utm_content=' + location.hostname + '&') + 'utm_campaign=poweredby';
return { url: url };
}
});
/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(0);
var _indexUtils = __webpack_require__(4);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var namespace = 'refinementList';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), [], function (currentRefinement) {
if (typeof currentRefinement === 'string') {
// All items were unselected
if (currentRefinement === '') {
return [];
}
// Only one item was in the searchState but we know it should be an array
return [currentRefinement];
}
return currentRefinement;
});
}
function getValue(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement(props, searchState, context);
var isAnewValue = currentRefinement.indexOf(name) === -1;
var nextRefinement = isAnewValue ? currentRefinement.concat([name]) : // cannot use .push(), it mutates
currentRefinement.filter(function (selectedValue) {
return selectedValue !== name;
}); // cannot use .splice(), it mutates
return nextRefinement;
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
// Setting the value to an empty string ensures that it is persisted in
// the URL as an empty value.
// This is necessary in the case where `defaultRefinement` contains one
// item and we try to deselect it. `nextSelected` would be an empty array,
// which would not be persisted to the URL.
// {foo: ['bar']} => "foo[0]=bar"
// {foo: []} => ""
var nextValue = _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectRefinementList connector provides the logic to build a widget that will
* give the user tha ability to choose multiple values for a specific facet.
* @name connectRefinementList
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of displayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var sortBy = ['isRefined', 'count:desc', 'name:asc'];
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: _react.PropTypes.string,
attributeName: _react.PropTypes.string.isRequired,
operator: _react.PropTypes.oneOf(['and', 'or']),
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
defaultRefinement: _react.PropTypes.arrayOf(_react.PropTypes.string),
withSearchBox: _react.PropTypes.bool,
searchForFacetValues: _react.PropTypes.bool, // @deprecated
transformItems: _react.PropTypes.func
},
defaultProps: {
operator: 'or',
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var _this = this;
var results = searchResults.results;
var attributeName = props.attributeName;
var showMore = props.showMore;
var limitMin = props.limitMin;
var limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var index = (0, _indexUtils.getIndex)(this.context);
var canRefine = Boolean(results) && Boolean(results[index]) && Boolean(results[index].getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.');
}
// Search For Facet Values is not available with derived helper (used for multi index search)
if (props.withSearchBox && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: canRefine,
isFromSearch: isFromSearch,
withSearchBox: withSearchBox
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results[index].getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) {
return {
label: v.name,
value: getValue(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName;
var operator = props.operator;
var showMore = props.showMore;
var limitMin = props.limitMin;
var limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet';
var addRefinementKey = addKey + 'Refinement';
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
searchParameters = searchParameters[addKey](attributeName);
return getCurrentRefinement(props, searchState, this.context).reduce(function (res, val) {
return res[addRefinementKey](attributeName, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId(props);
var context = this.context;
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: getCurrentRefinement(props, searchState, context).length > 0 ? [{
attributeName: props.attributeName,
label: props.attributeName + ': ',
currentRefinement: getCurrentRefinement(props, searchState, context),
value: function value(nextState) {
return _refine(props, nextState, [], context);
},
items: getCurrentRefinement(props, searchState, context).map(function (item) {
return {
label: '' + item,
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement(props, nextState, context).filter(function (other) {
return other !== item;
});
return _refine(props, searchState, nextSelectedItems, context);
}
};
})
}] : []
};
}
});
/***/ }),
/* 226 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectScrollTo connector provides the logic to build a widget that will
* let the page scroll to a certain point.
* @name connectScrollTo
* @kind connector
* @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget.
* @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: _react.PropTypes.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var id = props.scrollOn;
var value = (0, _indexUtils.getCurrentRefinementValue)(props, searchState, this.context, id, null, function (currentRefinement) {
return currentRefinement;
});
return { value: value };
}
});
/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _react = __webpack_require__(0);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'query';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId(props);
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, '', function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return '';
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, getId());
}
/**
* connectSearchBox connector provides the logic to build a widget that will
* let the user search for a query.
* @name connectSearchBox
* @kind connector
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the query to search for.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: _react.PropTypes.string
},
getProvidedProps: function getProvidedProps(props, searchState) {
return {
currentRefinement: getCurrentRefinement(props, searchState, this.context)
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context));
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: currentRefinement === null ? [] : [{
label: id + ': ' + currentRefinement,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _indexUtils = __webpack_require__(4);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'sortBy';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId(props);
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return null;
});
}
/**
* connectSortBy connector provides the logic to build a widget that will
* displays a list of indexes allowing a user to change the hits are sorting.
* @name connectSortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind connector
* @propType {string} defaultRefinement - The default selected index.
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaSortBy',
propTypes: {
defaultRefinement: _react.PropTypes.string,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string,
value: _react.PropTypes.string.isRequired
})).isRequired,
transformItems: _react.PropTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false });
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement(props, searchState, this.context);
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectStats connector provides the logic to build a widget that will
* displays algolia search statistics (hits number and processing time).
* @name connectStats
* @kind connector
* @providedPropType {number} nbHits - number of hits returned by Algolia.
* @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var index = (0, _indexUtils.getIndex)(this.context);
if (!searchResults.results || !searchResults.results[index]) {
return null;
}
return {
nbHits: searchResults.results[index].nbHits,
processingTimeMS: searchResults.results[index].processingTimeMS
};
}
});
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId(props) {
return props.attributeName;
}
var namespace = 'toggle';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), false, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return null;
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectToggle connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization.
* @name connectToggle
* @kind connector
* @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attributeName`.
* @propType {boolean} [defaultChecked=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaToggle',
propTypes: {
label: _react.PropTypes.string,
filter: _react.PropTypes.func,
attributeName: _react.PropTypes.string,
value: _react.PropTypes.any,
defaultRefinement: _react.PropTypes.bool
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return { currentRefinement: currentRefinement };
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName;
var value = props.value;
var filter = props.filter;
var checked = getCurrentRefinement(props, searchState, this.context);
if (checked) {
if (attributeName) {
searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value);
}
if (filter) {
searchParameters = filter(searchParameters);
}
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var checked = getCurrentRefinement(props, searchState, this.context);
var items = [];
var index = (0, _indexUtils.getIndex)(this.context);
if (checked) {
items.push({
label: props.label,
currentRefinement: props.label,
attributeName: props.attributeName,
value: function value(nextState) {
return _refine(props, nextState, false, _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHighlight = __webpack_require__(207);
var _connectHighlight2 = _interopRequireDefault(_connectHighlight);
var _Highlight = __webpack_require__(376);
var _Highlight2 = _interopRequireDefault(_Highlight);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Renders any attribute from an hit into its highlighted form when relevant.
*
* Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide.
* @name Highlight
* @kind widget
* @propType {string} attributeName - the location of the highlighted attribute in the hit
* @propType {object} hit - the hit object containing the highlighted attribute
* @example
* import React from 'react';
*
* import {InstantSearch, connectHits, Highlight} from 'InstantSearch';
*
* const CustomHits = connectHits(hits => {
* return hits.map((hit) => <p><Highlight attributeName="description" hit={hit}/></p>);
* });
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CustomHits />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHighlight2.default)(_Highlight2.default);
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(38);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(56);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Link = function (_Component) {
_inherits(Link, _Component);
function Link() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Link);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) {
if ((0, _utils.isSpecialClick)(e)) {
return;
}
_this.props.onClick();
e.preventDefault();
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Link, [{
key: 'render',
value: function render() {
return _react2.default.createElement('a', _extends({}, (0, _omit3.default)(this.props, 'onClick'), {
onClick: this.onClick
}));
}
}]);
return Link;
}(_react.Component);
Link.propTypes = {
onClick: _react.PropTypes.func.isRequired
};
exports.default = Link;
/***/ }),
/* 233 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get2 = __webpack_require__(70);
var _get3 = _interopRequireDefault(_get2);
exports.default = parseAlgoliaHit;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it,
* and provided an array of objects with the string value and a boolean if this
* value is highlighted.
*
* In order to use this feature, highlight must be activated in the configuration of
* the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and
* highligtPostTag in Algolia configuration.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightProperty - the property that contains the highlight structure in the results
* @param {string} attributeName - the highlighted attribute to look for
* @param {object} hit - the actual hit returned by Algolia.
* @return {object[]} - An array of {value: string, isDefined: boolean}.
*/
function parseAlgoliaHit(_ref) {
var _ref$preTag = _ref.preTag;
var preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag;
var _ref$postTag = _ref.postTag;
var postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag;
var highlightProperty = _ref.highlightProperty;
var attributeName = _ref.attributeName;
var hit = _ref.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = (0, _get3.default)(hit[highlightProperty], attributeName);
var highlightedValue = !highlightObject ? '' : highlightObject.value;
return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightedValue });
}
/**
* Parses an highlighted attribute into an array of objects with the string value, and
* a boolean that indicated if this part is highlighted.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature
* @return {object[]} - An array of {value: string, isDefined: boolean}.
*/
function parseHighlightedAttribute(_ref2) {
var preTag = _ref2.preTag;
var postTag = _ref2.postTag;
var highlightedValue = _ref2.highlightedValue;
var splitByPreTag = highlightedValue.split(preTag);
var firstValue = splitByPreTag.shift();
var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }];
if (postTag === preTag) {
var isHighlighted = true;
splitByPreTag.forEach(function (split) {
elements.push({ value: split, isHighlighted: isHighlighted });
isHighlighted = !isHighlighted;
});
} else {
splitByPreTag.forEach(function (split) {
var splitByPostTag = split.split(postTag);
elements.push({
value: splitByPostTag[0],
isHighlighted: true
});
if (splitByPostTag[1] !== '') {
elements.push({
value: splitByPostTag[1],
isHighlighted: false
});
}
});
}
return elements;
}
/***/ }),
/* 234 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 235 */
/***/ (function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(113);
var events = __webpack_require__(112);
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
*/
function DerivedHelper(mainHelper, fn) {
this.main = mainHelper;
this.fn = fn;
this.lastResults = null;
}
util.inherits(DerivedHelper, events.EventEmitter);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper.prototype.detach = function() {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper.prototype.getModifiedState = function(parameters) {
return this.fn(parameters);
};
module.exports = DerivedHelper;
/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var isUndefined = __webpack_require__(200);
var isString = __webpack_require__(49);
var isFunction = __webpack_require__(18);
var isEmpty = __webpack_require__(17);
var defaults = __webpack_require__(99);
var reduce = __webpack_require__(51);
var filter = __webpack_require__(100);
var omit = __webpack_require__(38);
var lib = {
/**
* Adds a refinement to a RefinementList
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated prefinement list
*/
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) {
return refinementList;
}
var valueAsString = '' + value;
var facetRefinement = !refinementList[attribute] ?
[valueAsString] :
refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaults({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (isUndefined(value)) {
return lib.clearRefinement(refinementList, attribute);
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* behaviors can happen:
* - if no attribute is provided: clears the whole list
* - if an attribute is provided as a string: clears the list for the specific attribute
* - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optionnal parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(refinementList, attribute);
} else if (isFunction(attribute)) {
return reduce(refinementList, function(memo, values, key) {
var facetList = filter(values, function(value) {
return !attribute(value, key, refinementType);
});
if (!isEmpty(facetList)) memo[key] = facetList;
return memo;
}, {});
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var indexOf = __webpack_require__(71);
var containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (isUndefined(refinementValue) || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return indexOf(refinementList[attribute], refinementValueAsString) !== -1;
}
};
module.exports = lib;
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(34);
var filter = __webpack_require__(100);
var map = __webpack_require__(15);
var isEmpty = __webpack_require__(17);
var indexOf = __webpack_require__(71);
function filterState(state, filters) {
var partialState = {};
var attributeFilters = filter(filters, function(f) { return f.indexOf('attribute:') !== -1; });
var attributes = map(attributeFilters, function(aF) { return aF.split(':')[1]; });
if (indexOf(attributes, '*') === -1) {
forEach(attributes, function(attr) {
if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) {
if (!partialState.facetsRefinements) partialState.facetsRefinements = {};
partialState.facetsRefinements[attr] = state.facetsRefinements[attr];
}
if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) {
if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {};
partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr];
}
if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) {
if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {};
partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr];
}
var numericRefinements = state.getNumericRefinements(attr);
if (!isEmpty(numericRefinements)) {
if (!partialState.numericRefinements) partialState.numericRefinements = {};
partialState.numericRefinements[attr] = state.numericRefinements[attr];
}
});
} else {
if (!isEmpty(state.numericRefinements)) {
partialState.numericRefinements = state.numericRefinements;
}
if (!isEmpty(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements;
if (!isEmpty(state.disjunctiveFacetsRefinements)) {
partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements;
}
if (!isEmpty(state.hierarchicalFacetsRefinements)) {
partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements;
}
}
var searchParameters = filter(
filters,
function(f) {
return f.indexOf('attribute:') === -1;
}
);
forEach(
searchParameters,
function(parameterKey) {
partialState[parameterKey] = state[parameterKey];
}
);
return partialState;
}
module.exports = filterState;
/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var invert = __webpack_require__(198);
var keys = __webpack_require__(8);
var keys2Short = {
advancedSyntax: 'aS',
allowTyposOnNumericTokens: 'aTONT',
analyticsTags: 'aT',
analytics: 'a',
aroundLatLngViaIP: 'aLLVIP',
aroundLatLng: 'aLL',
aroundPrecision: 'aP',
aroundRadius: 'aR',
attributesToHighlight: 'aTH',
attributesToRetrieve: 'aTR',
attributesToSnippet: 'aTS',
disjunctiveFacetsRefinements: 'dFR',
disjunctiveFacets: 'dF',
distinct: 'd',
facetsExcludes: 'fE',
facetsRefinements: 'fR',
facets: 'f',
getRankingInfo: 'gRI',
hierarchicalFacetsRefinements: 'hFR',
hierarchicalFacets: 'hF',
highlightPostTag: 'hPoT',
highlightPreTag: 'hPrT',
hitsPerPage: 'hPP',
ignorePlurals: 'iP',
index: 'idx',
insideBoundingBox: 'iBB',
insidePolygon: 'iPg',
length: 'l',
maxValuesPerFacet: 'mVPF',
minimumAroundRadius: 'mAR',
minProximity: 'mP',
minWordSizefor1Typo: 'mWS1T',
minWordSizefor2Typos: 'mWS2T',
numericFilters: 'nF',
numericRefinements: 'nR',
offset: 'o',
optionalWords: 'oW',
page: 'p',
queryType: 'qT',
query: 'q',
removeWordsIfNoResults: 'rWINR',
replaceSynonymsInHighlight: 'rSIH',
restrictSearchableAttributes: 'rSA',
synonyms: 's',
tagFilters: 'tF',
tagRefinements: 'tR',
typoTolerance: 'tT',
optionalTagFilters: 'oTF',
optionalFacetFilters: 'oFF',
snippetEllipsisText: 'sET',
disableExactOnAttributes: 'dEOA',
enableExactOnSingleWordQuery: 'eEOSWQ'
};
var short2Keys = invert(keys2Short);
module.exports = {
/**
* All the keys of the state, encoded.
* @const
*/
ENCODED_PARAMETERS: keys(short2Keys),
/**
* Decode a shorten attribute
* @param {string} shortKey the shorten attribute
* @return {string} the decoded attribute, undefined otherwise
*/
decode: function(shortKey) {
return short2Keys[shortKey];
},
/**
* Encode an attribute into a short version
* @param {string} key the attribute
* @return {string} the shorten attribute
*/
encode: function(key) {
return keys2Short[key];
}
};
/***/ }),
/* 240 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = generateTrees;
var last = __webpack_require__(201);
var map = __webpack_require__(15);
var reduce = __webpack_require__(51);
var orderBy = __webpack_require__(105);
var trim = __webpack_require__(204);
var find = __webpack_require__(47);
var pickBy = __webpack_require__(330);
var prepareHierarchicalFacetSortBy = __webpack_require__(115);
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
}
return reduce(results, generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
data: null
});
};
}
function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
parent = parent && find(parent.data, {isRefined: true});
level++;
}
}
// we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath,
currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
parent.data = orderBy(
map(
pickBy(hierarchicalFacetResult.data, onlyMatchingValuesFn),
formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement)
),
sortBy[0], sortBy[1]
);
}
return hierarchicalTree;
};
}
function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel) {
return function(facetCount, facetValue) {
// we want the facetValue is a child of hierarchicalRootPath
if (hierarchicalRootPath &&
(facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) {
return false;
}
// we always want root levels (only when there is no prefix path)
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 ||
// if there is a rootPath, being root level mean 1 level under rootPath
hierarchicalRootPath &&
facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 ||
// if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
facetValue.indexOf(hierarchicalSeparator) === -1 &&
currentRefinement.indexOf(hierarchicalSeparator) === -1 ||
// currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 ||
// facetValue is a child of the current parent, add it
facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 &&
(hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
};
}
function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) {
return function format(facetCount, facetValue) {
return {
name: trim(last(facetValue.split(hierarchicalSeparator))),
path: facetValue,
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
data: null
};
};
}
/***/ }),
/* 241 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var SearchParameters = __webpack_require__(77);
var SearchResults = __webpack_require__(114);
var DerivedHelper = __webpack_require__(236);
var requestBuilder = __webpack_require__(243);
var util = __webpack_require__(113);
var events = __webpack_require__(112);
var flatten = __webpack_require__(196);
var forEach = __webpack_require__(34);
var isEmpty = __webpack_require__(17);
var map = __webpack_require__(15);
var url = __webpack_require__(116);
var version = __webpack_require__(117);
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {SearchParameters} state the current parameters with the latest changes applied
* @property {SearchResults} lastResults the previous results received from Algolia. `null` before
* the first request
* @example
* helper.on('change', function(state, lastResults) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when the search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {SearchParameters} state the parameters used for this search
* @property {SearchResults} lastResults the results from the previous search. `null` if
* it is the first search.
* @example
* helper.on('search', function(state, lastResults) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {SearchResults} results the results received from Algolia
* @property {SearchParameters} state the parameters used to query Algolia. Those might
* be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(results, state) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {Error} error the error returned by the Algolia.
* @example
* helper.on('error', function(error) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line
else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version);
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
}
util.inherits(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occcurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function() {
this._search();
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper.prototype.getQuery = function() {
var state = this.state;
return requestBuilder._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occured it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder._getQueries(tempState.index, tempState);
if (cb) {
return this.client.search(
queries,
function(err, content) {
if (err) cb(err, null, tempState);
else cb(err, new SearchResults(tempState, content.results), tempState);
}
);
}
return this.client.search(queries).then(function(content) {
return {
content: new SearchResults(tempState, content.results),
state: tempState,
_originalResponse: content
};
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {objet}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query insde the engine
*/
/**
* Search for facet values based on an query and the name of a facetted attribute. This
* triggers a search and will retrun a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} query the string query for the search
* @param {string} facet the name of the facetted attribute
* @return {promise<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query) {
var state = this.state;
var index = this.client.initIndex(this.state.index);
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, this.state);
return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) {
content.facetHits = forEach(content.facetHits, function(f) {
f.isRefined = isDisjunctive ?
state.isDisjunctiveFacetRefined(facet, f.value) :
state.isFacetRefined(facet, f.value);
});
return content;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this.state = this.state.setPage(0).setQuery(q);
this._change();
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this.state = this.state.setPage(0).clearRefinements(name);
this._change();
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this.state = this.state.setPage(0).clearTags();
this._change();
return this;
};
/**
* Adds a disjunctive filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value);
this._change();
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Adds a filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).addExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this.state = this.state.setPage(0).addTagRefinement(tag);
this._change();
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optionnals, triggering different behaviors:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Removes a disjunctive filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet);
this._change();
return this;
};
/**
* Removes a filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).removeExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this.state = this.state.setPage(0).removeTagRefinement(tag);
this._change();
return this;
};
/**
* Adds or removes an exclusion filter to a facetted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a facetted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a facetted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).toggleFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this.state = this.state.setPage(0).toggleTagRefinement(tag);
this._change();
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
return this.setPage(this.state.page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
return this.setPage(this.state.page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this.state = this.state.setPage(page);
this._change();
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this.state = this.state.setPage(0).setIndex(name);
this._change();
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
var newState = this.state.setPage(0).setQueryParameter(parameter, value);
if (this.state === newState) return this;
this.state = newState;
this._change();
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this.state = new SearchParameters(newState);
this._change();
return this;
};
/**
* Get the current search state stored in the helper. This object is immutable.
* @param {string[]} [filters] optionnal filters to retrieve only a subset of the state
* @return {SearchParameters|object} if filters is specified a plain object is
* returned containing only the requested fields, otherwise return the unfiltered
* state
* @example
* // Get the complete state as stored in the helper
* helper.getState();
* @example
* // Get a part of the state with all the refinements on attributes and the query
* helper.getState(['query', 'attribute:category']);
*/
AlgoliaSearchHelper.prototype.getState = function(filters) {
if (filters === undefined) return this.state;
return this.state.filter(filters);
};
/**
* DEPRECATED Get part of the state as a query string. By default, the output keys will not
* be prefixed and will only take the applied refinements and the query.
* @deprecated
* @param {object} [options] May contain the following parameters :
*
* **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for
* the index, all the refinements with `attribute:*` or for some specific attributes with
* `attribute:theAttribute`
*
* **prefix** : prefix in front of the keys
*
* **moreAttributes** : more values to be added in the query string. Those values
* won't be prefixed.
* @return {string} the query string
*/
AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) {
var filters = options && options.filters || ['query', 'attribute:*'];
var partialState = this.getState(filters);
return url.getQueryStringFromState(partialState, options);
};
/**
* DEPRECATED Read a query string and return an object containing the state. Use
* url module.
* @deprecated
* @static
* @param {string} queryString the query string that will be decoded
* @param {object} options accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
* @see {@link url#getStateFromQueryString}
*/
AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString;
/**
* DEPRECATED Retrieve an object of all the properties that are not understandable as helper
* parameters. Use url module.
* @deprecated
* @static
* @param {string} queryString the query string to read
* @param {object} options the options
* - prefixForParameters : prefix used for the helper configuration keys
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString;
/**
* DEPRECATED Overrides part of the state with the properties stored in the provided query
* string.
* @deprecated
* @param {string} queryString the query string containing the informations to url the state
* @param {object} options optionnal parameters :
* - prefix : prefix used for the algolia parameters
* - triggerChange : if set to true the state update will trigger a change event
*/
AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) {
var triggerChange = options && options.triggerChange || false;
var configuration = url.getStateFromQueryString(queryString, options);
var updatedState = this.state.setQueryParameters(configuration);
if (triggerChange) this.setState(updatedState);
else this.overrideStateWithoutTriggeringChangeEvent(updatedState);
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters(newState);
return this;
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isRefined = function(facet, value) {
if (this.state.isConjunctiveFacet(facet)) {
return this.state.isFacetRefined(facet, value);
} else if (this.state.isDisjunctiveFacet(facet)) {
return this.state.isDisjunctiveFacetRefined(facet, value);
}
throw new Error(facet +
' is not properly defined in this helper configuration' +
'(use the facets or disjunctiveFacets keys to configure it)');
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (!isEmpty(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific facetted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for facetting
* @param {string} [value] optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean}
*/
AlgoliaSearchHelper.prototype.hasTag = function(tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper.prototype.isTagRefined = function() {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string}
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper.prototype.getIndex = function() {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper.prototype.getTags = function() {
return this.state.tagRefinements;
};
/**
* Get a parameter of the search by its name. It is possible that a parameter is directly
* defined in the index dashboard, but it will be undefined using this method.
*
* The complete list of parameters is
* available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters have their own API)
* @param {string} parameterName the parameter name
* @return {any} the parameter value
* @example
* var hitsPerPage = helper.getQueryParameter('hitsPerPage');
*/
AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) {
return this.state.getQueryParameter(parameterName);
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for facetting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper.prototype.getRefinements = function(facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
forEach(conjRefinements, function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
forEach(excludeRefinements, function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
forEach(disjRefinements, function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
forEach(numericRefinements, function(value, operator) {
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
// /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function() {
var state = this.state;
var mainQueries = requestBuilder._getQueries(state.index, state);
var states = [{
state: state,
queriesCount: mainQueries.length,
helper: this
}];
this.emit('search', state, this.lastResults);
var derivedQueries = map(this.derivedHelpers, function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var queries = requestBuilder._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: queries.length,
helper: derivedHelper
});
derivedHelper.emit('search', derivedState, derivedHelper.lastResults);
return queries;
});
var queries = mainQueries.concat(flatten(derivedQueries));
var queryId = this._queryId++;
this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId));
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable objet that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>}
* state state used for to generate the request
* @param {number} queryId id of the current request
* @param {Error} err error if any, null otherwise
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) {
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._lastQueryIdReceived = queryId;
if (err) {
this.emit('error', err);
return;
}
var results = content.results;
forEach(states, function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults(state, specificResults);
helper.emit('result', formattedResponse, state);
});
};
AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
facetFilters.length !== 0 ||
numericFilters.length !== 0 ||
tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] &&
this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function() {
this.emit('change', this.state, this.lastResults);
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.setClient = function(newClient) {
if (this.client === newClient) return this;
if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version);
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch}
*/
AlgoliaSearchHelper.prototype.getClient = function() {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `result` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @return {DerivedHelper}
*/
AlgoliaSearchHelper.prototype.derive = function(fn) {
var derivedHelper = new DerivedHelper(this, fn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @return {undefined}
* @throws Error
*/
AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error('Derived helper already detached');
this.derivedHelpers.splice(pos, 1);
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the facetting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
/*
* This function tests if the _ua parameter of the client
* already contains the JS Helper UA
*/
function doesClientAgentContainsHelper(client) {
// this relies on JS Client internal variable, this might break if implementation changes
var currentAgent = client._ua;
return !currentAgent ? false :
currentAgent.indexOf('JS Helper') !== -1;
}
module.exports = AlgoliaSearchHelper;
/***/ }),
/* 242 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var map = __webpack_require__(15);
var isArray = __webpack_require__(1);
var isNumber = __webpack_require__(199);
var isString = __webpack_require__(49);
function valToNumber(v) {
if (isNumber(v)) {
return v;
} else if (isString(v)) {
return parseFloat(v);
} else if (isArray(v)) {
return map(v, valToNumber);
}
throw new Error('The value should be a number, a parseable string or an array of those.');
}
module.exports = valToNumber;
/***/ }),
/* 243 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(34);
var map = __webpack_require__(15);
var reduce = __webpack_require__(51);
var merge = __webpack_require__(104);
var isArray = __webpack_require__(1);
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = [];
// One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
});
// One for each disjunctive facets
forEach(state.getRefinedDisjunctiveFacets(), function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function(state) {
var facets = state.facets
.concat(state.disjunctiveFacets)
.concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(
state,
hierarchicalFacet,
hierarchicalRootLevel
);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
forEach(state.numericRefinements, function(operators, attribute) {
forEach(operators, function(values, operator) {
if (facetName !== attribute) {
forEach(values, function(value) {
if (isArray(value)) {
var vs = map(value, function(v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
forEach(state.facetsRefinements, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
forEach(state.facetsExcludes, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
forEach(state.disjunctiveFacetsRefinements, function(facetValues, facetName) {
if (facetName === facet || !facetValues || facetValues.length === 0) return;
var orFilters = [];
forEach(facetValues, function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
forEach(state.hierarchicalFacetsRefinements, function(facetValues, facetName) {
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
// we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) ||
(rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return reduce(
state.hierarchicalFacets,
// ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
// if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || '';
// if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function(facetName, query, state) {
var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ?
state.clearRefinements(facetName) :
state;
var queries = merge(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), {
facetQuery: query,
facetName: facetName
});
return queries;
}
};
module.exports = requestBuilder;
/***/ }),
/* 244 */
/***/ (function(module, exports, __webpack_require__) {
var foreach = __webpack_require__(109);
module.exports = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
/***/ }),
/* 245 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/* 246 */
/***/ (function(module, exports) {
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
module.exports = addMapEntry;
/***/ }),
/* 247 */
/***/ (function(module, exports) {
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
module.exports = addSetEntry;
/***/ }),
/* 248 */
/***/ (function(module, exports) {
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
module.exports = asciiToArray;
/***/ }),
/* 249 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
keys = __webpack_require__(8);
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
module.exports = baseAssign;
/***/ }),
/* 250 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
keysIn = __webpack_require__(50);
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
module.exports = baseAssignIn;
/***/ }),
/* 251 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
module.exports = baseClamp;
/***/ }),
/* 252 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(41),
arrayEach = __webpack_require__(81),
assignValue = __webpack_require__(86),
baseAssign = __webpack_require__(249),
baseAssignIn = __webpack_require__(250),
cloneBuffer = __webpack_require__(141),
copyArray = __webpack_require__(66),
copySymbols = __webpack_require__(287),
copySymbolsIn = __webpack_require__(288),
getAllKeys = __webpack_require__(91),
getAllKeysIn = __webpack_require__(92),
getTag = __webpack_require__(55),
initCloneArray = __webpack_require__(303),
initCloneByTag = __webpack_require__(304),
initCloneObject = __webpack_require__(162),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(25),
isObject = __webpack_require__(5),
keys = __webpack_require__(8);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
module.exports = baseClone;
/***/ }),
/* 253 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(57),
arrayIncludes = __webpack_require__(83),
arrayIncludesWith = __webpack_require__(124),
arrayMap = __webpack_require__(11),
baseUnary = __webpack_require__(45),
cacheHas = __webpack_require__(65);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
module.exports = baseDifference;
/***/ }),
/* 254 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(61);
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
module.exports = baseFilter;
/***/ }),
/* 255 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
module.exports = baseHasIn;
/***/ }),
/* 256 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(57),
arrayIncludes = __webpack_require__(83),
arrayIncludesWith = __webpack_require__(124),
arrayMap = __webpack_require__(11),
baseUnary = __webpack_require__(45),
cacheHas = __webpack_require__(65);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
module.exports = baseIntersection;
/***/ }),
/* 257 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(43);
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
module.exports = baseInverter;
/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(41),
baseIsEqual = __webpack_require__(63);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
/***/ }),
/* 259 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
module.exports = baseIsNaN;
/***/ }),
/* 260 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(5),
isPrototype = __webpack_require__(36),
nativeKeysIn = __webpack_require__(309);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = baseKeysIn;
/***/ }),
/* 261 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsMatch = __webpack_require__(258),
getMatchData = __webpack_require__(300),
matchesStrictComparable = __webpack_require__(176);
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
module.exports = baseMatches;
/***/ }),
/* 262 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(63),
get = __webpack_require__(70),
hasIn = __webpack_require__(197),
isKey = __webpack_require__(69),
isStrictComparable = __webpack_require__(165),
matchesStrictComparable = __webpack_require__(176),
toKey = __webpack_require__(22);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
module.exports = baseMatchesProperty;
/***/ }),
/* 263 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(41),
assignMergeValue = __webpack_require__(126),
baseFor = __webpack_require__(129),
baseMergeDeep = __webpack_require__(264),
isObject = __webpack_require__(5),
keysIn = __webpack_require__(50);
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
if (isObject(srcValue)) {
stack || (stack = new Stack);
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(object[key], srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
module.exports = baseMerge;
/***/ }),
/* 264 */
/***/ (function(module, exports, __webpack_require__) {
var assignMergeValue = __webpack_require__(126),
cloneBuffer = __webpack_require__(141),
cloneTypedArray = __webpack_require__(142),
copyArray = __webpack_require__(66),
initCloneObject = __webpack_require__(162),
isArguments = __webpack_require__(24),
isArray = __webpack_require__(1),
isArrayLikeObject = __webpack_require__(101),
isBuffer = __webpack_require__(25),
isFunction = __webpack_require__(18),
isObject = __webpack_require__(5),
isPlainObject = __webpack_require__(103),
isTypedArray = __webpack_require__(35),
toPlainObject = __webpack_require__(335);
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = object[key],
srcValue = source[key],
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
module.exports = baseMergeDeep;
/***/ }),
/* 265 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseIteratee = __webpack_require__(12),
baseMap = __webpack_require__(135),
baseSortBy = __webpack_require__(272),
baseUnary = __webpack_require__(45),
compareMultiple = __webpack_require__(286),
identity = __webpack_require__(23);
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
var index = -1;
iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
module.exports = baseOrderBy;
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
var basePickBy = __webpack_require__(136),
hasIn = __webpack_require__(197);
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
module.exports = basePick;
/***/ }),
/* 267 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(62);
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
module.exports = basePropertyDeep;
/***/ }),
/* 269 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
module.exports = baseReduce;
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(86),
castPath = __webpack_require__(20),
isIndex = __webpack_require__(30),
isObject = __webpack_require__(5),
toKey = __webpack_require__(22);
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
module.exports = baseSet;
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(194),
defineProperty = __webpack_require__(149),
identity = __webpack_require__(23);
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
module.exports = baseSetToString;
/***/ }),
/* 272 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
module.exports = baseSortBy;
/***/ }),
/* 273 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
module.exports = baseSum;
/***/ }),
/* 274 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(20),
last = __webpack_require__(201),
parent = __webpack_require__(310),
toKey = __webpack_require__(22);
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
module.exports = baseUnset;
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11);
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
module.exports = baseValues;
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLikeObject = __webpack_require__(101);
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
module.exports = castArrayLikeObject;
/***/ }),
/* 277 */
/***/ (function(module, exports, __webpack_require__) {
var baseSlice = __webpack_require__(138);
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
module.exports = castSlice;
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(44);
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsEndIndex;
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(44);
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsStartIndex;
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(89);
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
module.exports = cloneDataView;
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
var addMapEntry = __webpack_require__(246),
arrayReduce = __webpack_require__(85),
mapToArray = __webpack_require__(95);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map);
return arrayReduce(array, addMapEntry, new map.constructor);
}
module.exports = cloneMap;
/***/ }),
/* 282 */
/***/ (function(module, exports) {
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
module.exports = cloneRegExp;
/***/ }),
/* 283 */
/***/ (function(module, exports, __webpack_require__) {
var addSetEntry = __webpack_require__(247),
arrayReduce = __webpack_require__(85),
setToArray = __webpack_require__(97);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set);
return arrayReduce(array, addSetEntry, new set.constructor);
}
module.exports = cloneSet;
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(14);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
module.exports = cloneSymbol;
/***/ }),
/* 285 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(26);
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
module.exports = compareAscending;
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
var compareAscending = __webpack_require__(285);
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
module.exports = compareMultiple;
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
getSymbols = __webpack_require__(68);
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
module.exports = copySymbols;
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
getSymbolsIn = __webpack_require__(155);
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
module.exports = copySymbolsIn;
/***/ }),
/* 289 */
/***/ (function(module, exports) {
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
module.exports = countHolders;
/***/ }),
/* 290 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(10);
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
module.exports = createBaseEach;
/***/ }),
/* 291 */
/***/ (function(module, exports) {
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
var createCtor = __webpack_require__(67),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
module.exports = createBind;
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(58),
createCtor = __webpack_require__(67),
createHybrid = __webpack_require__(147),
createRecurry = __webpack_require__(148),
getHolder = __webpack_require__(46),
replaceHolders = __webpack_require__(33),
root = __webpack_require__(3);
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
module.exports = createCurry;
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(12),
isArrayLike = __webpack_require__(10),
keys = __webpack_require__(8);
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
module.exports = createFind;
/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {
var baseInverter = __webpack_require__(257);
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
module.exports = createInverter;
/***/ }),
/* 296 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(58),
createCtor = __webpack_require__(67),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
module.exports = createPartial;
/***/ }),
/* 297 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(16);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
module.exports = customDefaultsAssignIn;
/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {
var isPlainObject = __webpack_require__(103);
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
module.exports = customOmitClone;
/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {
var realNames = __webpack_require__(311);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
module.exports = getFuncName;
/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {
var isStrictComparable = __webpack_require__(165),
keys = __webpack_require__(8);
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
module.exports = getMatchData;
/***/ }),
/* 301 */
/***/ (function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
module.exports = getWrapDetails;
/***/ }),
/* 302 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
module.exports = hasUnicode;
/***/ }),
/* 303 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
module.exports = initCloneArray;
/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(89),
cloneDataView = __webpack_require__(280),
cloneMap = __webpack_require__(281),
cloneRegExp = __webpack_require__(282),
cloneSet = __webpack_require__(283),
cloneSymbol = __webpack_require__(284),
cloneTypedArray = __webpack_require__(142);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return cloneMap(object, isDeep, cloneFunc);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return cloneSymbol(object);
}
}
module.exports = initCloneByTag;
/***/ }),
/* 305 */
/***/ (function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
module.exports = insertWrapDetails;
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(14),
isArguments = __webpack_require__(24),
isArray = __webpack_require__(1);
/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
module.exports = isFlattenable;
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(78),
getData = __webpack_require__(153),
getFuncName = __webpack_require__(299),
lodash = __webpack_require__(337);
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
module.exports = isLaziable;
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(143),
composeArgsRight = __webpack_require__(144),
replaceHolders = __webpack_require__(33);
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
module.exports = mergeData;
/***/ }),
/* 309 */
/***/ (function(module, exports) {
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
module.exports = nativeKeysIn;
/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(62),
baseSlice = __webpack_require__(138);
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
module.exports = parent;
/***/ }),
/* 311 */
/***/ (function(module, exports) {
/** Used to lookup unminified function names. */
var realNames = {};
module.exports = realNames;
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
var copyArray = __webpack_require__(66),
isIndex = __webpack_require__(30);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
module.exports = reorder;
/***/ }),
/* 313 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = strictIndexOf;
/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {
var asciiToArray = __webpack_require__(248),
hasUnicode = __webpack_require__(302),
unicodeToArray = __webpack_require__(315);
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
module.exports = stringToArray;
/***/ }),
/* 315 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
module.exports = unicodeToArray;
/***/ }),
/* 316 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(81),
arrayIncludes = __webpack_require__(83);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
module.exports = updateWrapDetails;
/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(78),
LodashWrapper = __webpack_require__(121),
copyArray = __webpack_require__(66);
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
module.exports = wrapperClone;
/***/ }),
/* 318 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
createAssigner = __webpack_require__(146),
keysIn = __webpack_require__(50);
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
module.exports = assignInWith;
/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(19),
createWrap = __webpack_require__(90),
getHolder = __webpack_require__(46),
replaceHolders = __webpack_require__(33);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
// Assign default placeholders.
bind.placeholder = {};
module.exports = bind;
/***/ }),
/* 320 */
/***/ (function(module, exports) {
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = compact;
/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {
var baseDifference = __webpack_require__(253),
baseFlatten = __webpack_require__(128),
baseRest = __webpack_require__(19),
isArrayLikeObject = __webpack_require__(101);
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
module.exports = difference;
/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(43),
castFunction = __webpack_require__(140);
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, castFunction(iteratee));
}
module.exports = forOwn;
/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(44),
isArrayLike = __webpack_require__(10),
isString = __webpack_require__(49),
toInteger = __webpack_require__(52),
values = __webpack_require__(336);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
module.exports = includes;
/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseIntersection = __webpack_require__(256),
baseRest = __webpack_require__(19),
castArrayLikeObject = __webpack_require__(276);
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
module.exports = intersection;
/***/ }),
/* 325 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(42),
baseForOwn = __webpack_require__(43),
baseIteratee = __webpack_require__(12);
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
module.exports = mapKeys;
/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(42),
baseForOwn = __webpack_require__(43),
baseIteratee = __webpack_require__(12);
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
module.exports = mapValues;
/***/ }),
/* 327 */
/***/ (function(module, exports) {
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
module.exports = noop;
/***/ }),
/* 328 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(19),
createWrap = __webpack_require__(90),
getHolder = __webpack_require__(46),
replaceHolders = __webpack_require__(33);
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partial.placeholder = {};
module.exports = partial;
/***/ }),
/* 329 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(19),
createWrap = __webpack_require__(90),
getHolder = __webpack_require__(46),
replaceHolders = __webpack_require__(33);
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partialRight.placeholder = {};
module.exports = partialRight;
/***/ }),
/* 330 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseIteratee = __webpack_require__(12),
basePickBy = __webpack_require__(136),
getAllKeysIn = __webpack_require__(92);
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = baseIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
module.exports = pickBy;
/***/ }),
/* 331 */
/***/ (function(module, exports, __webpack_require__) {
var baseProperty = __webpack_require__(267),
basePropertyDeep = __webpack_require__(268),
isKey = __webpack_require__(69),
toKey = __webpack_require__(22);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
module.exports = property;
/***/ }),
/* 332 */
/***/ (function(module, exports, __webpack_require__) {
var baseClamp = __webpack_require__(251),
baseToString = __webpack_require__(64),
toInteger = __webpack_require__(52),
toString = __webpack_require__(72);
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
module.exports = startsWith;
/***/ }),
/* 333 */
/***/ (function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(12),
baseSum = __webpack_require__(273);
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, baseIteratee(iteratee, 2))
: 0;
}
module.exports = sumBy;
/***/ }),
/* 334 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(5),
isSymbol = __webpack_require__(26);
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = toNumber;
/***/ }),
/* 335 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
keysIn = __webpack_require__(50);
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
module.exports = toPlainObject;
/***/ }),
/* 336 */
/***/ (function(module, exports, __webpack_require__) {
var baseValues = __webpack_require__(275),
keys = __webpack_require__(8);
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
module.exports = values;
/***/ }),
/* 337 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(78),
LodashWrapper = __webpack_require__(121),
baseLodash = __webpack_require__(88),
isArray = __webpack_require__(1),
isObjectLike = __webpack_require__(6),
wrapperClone = __webpack_require__(317);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
module.exports = lodash;
/***/ }),
/* 338 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var stringify = __webpack_require__(340);
var parse = __webpack_require__(339);
var formats = __webpack_require__(205);
module.exports = {
formats: formats,
parse: parse,
stringify: stringify
};
/***/ }),
/* 339 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(107);
var has = Object.prototype.hasOwnProperty;
var defaults = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
decoder: utils.decode,
delimiter: '&',
depth: 5,
parameterLimit: 1000,
plainObjects: false,
strictNullHandling: false
};
var parseValues = function parseValues(str, options) {
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1));
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function parseObject(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index) &&
root !== cleanRoot &&
String(index) === cleanRoot &&
index >= 0 &&
(options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = parseObject(chain, val, options);
}
}
return obj;
};
var parseKeys = function parseKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey;
// The regex chunks
var parent = /^([^\[\]]*)/;
var child = /(\[[^\[\]]*\])/g;
// Get the parent
var segment = parent.exec(key);
// Stash the parent if it exists
var keys = [];
if (segment[1]) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, segment[1])) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) {
if (!options.allowPrototypes) {
continue;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
module.exports = function (str, opts) {
var options = opts || {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
/***/ }),
/* 340 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(107);
var formats = __webpack_require__(205);
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + '[]';
},
indices: function indices(prefix, key) {
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) {
return prefix;
}
};
var toISO = Date.prototype.toISOString;
var defaults = {
delimiter: '&',
encode: true,
encoder: utils.encode,
serializeDate: function serializeDate(date) {
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (obj === null) {
if (strictNullHandling) {
return encoder ? encoder(prefix) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
if (encoder) {
return [formatter(encoder(prefix)) + '=' + formatter(encoder(obj))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(
obj[key],
generateArrayPrefix(prefix, key),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
} else {
values = values.concat(stringify(
obj[key],
prefix + (allowDots ? '.' + key : '[' + key + ']'),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
}
}
return values;
};
module.exports = function (object, opts) {
var obj = object;
var options = opts || {};
var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null;
var sort = typeof options.sort === 'function' ? options.sort : null;
var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
if (typeof options.format === 'undefined') {
options.format = formats.default;
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.');
}
var formatter = formats.formatters[options.format];
var objKeys;
var filter;
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(
obj[key],
key,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
}
return keys.join(delimiter);
};
/***/ }),
/* 341 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Highlighter;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Highlighter(_ref) {
var hit = _ref.hit;
var attributeName = _ref.attributeName;
var highlight = _ref.highlight;
var highlightProperty = _ref.highlightProperty;
var parsedHighlightedValue = highlight({ hit: hit, attributeName: attributeName, highlightProperty: highlightProperty });
var reactHighlighted = parsedHighlightedValue.map(function (v, i) {
var key = "split-" + i + "-" + v.value;
if (!v.isHighlighted) {
return _react2.default.createElement(
"span",
{ key: key, className: "ais-Highlight__nonHighlighted" },
v.value
);
}
return _react2.default.createElement(
"em",
{ key: key, className: "ais-Highlight__highlighted" },
v.value
);
});
return _react2.default.createElement(
"span",
{ className: "ais-Highlight" },
reactHighlighted
);
}
Highlighter.propTypes = {
hit: _react2.default.PropTypes.object.isRequired,
attributeName: _react2.default.PropTypes.string.isRequired,
highlight: _react2.default.PropTypes.func.isRequired,
highlightProperty: _react2.default.PropTypes.string.isRequired
};
/***/ }),
/* 342 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('SearchBox');
var SearchBox = function (_Component) {
_inherits(SearchBox, _Component);
function SearchBox(props) {
_classCallCheck(this, SearchBox);
var _this = _possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this));
_this.getQuery = function () {
return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query;
};
_this.setQuery = function (val) {
var _this$props = _this.props;
var refine = _this$props.refine;
var searchAsYouType = _this$props.searchAsYouType;
if (searchAsYouType) {
refine(val);
} else {
_this.setState({
query: val
});
}
};
_this.onInputMount = function (input) {
_this.input = input;
if (_this.props.__inputRef) {
_this.props.__inputRef(input);
}
};
_this.onKeyDown = function (e) {
if (!_this.props.focusShortcuts) {
return;
}
var shortcuts = _this.props.focusShortcuts.map(function (key) {
return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key;
});
var elt = e.target || e.srcElement;
var tagName = elt.tagName;
if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') {
// already in an input
return;
}
var which = e.which || e.keyCode;
if (shortcuts.indexOf(which) === -1) {
// not the right shortcut
return;
}
_this.input.focus();
e.stopPropagation();
e.preventDefault();
};
_this.onSubmit = function (e) {
e.preventDefault();
e.stopPropagation();
_this.input.blur();
var _this$props2 = _this.props;
var refine = _this$props2.refine;
var searchAsYouType = _this$props2.searchAsYouType;
if (!searchAsYouType) {
refine(_this.getQuery());
}
return false;
};
_this.onChange = function (e) {
_this.setQuery(e.target.value);
if (_this.props.onChange) {
_this.props.onChange(e);
}
};
_this.onReset = function () {
_this.setQuery('');
_this.input.focus();
if (_this.props.onReset) {
_this.props.onReset();
}
};
_this.state = {
query: props.searchAsYouType ? null : props.currentRefinement
};
return _this;
}
_createClass(SearchBox, [{
key: 'componentDidMount',
value: function componentDidMount() {
document.addEventListener('keydown', this.onKeyDown);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
document.removeEventListener('keydown', this.onKeyDown);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
// Reset query when the searchParameters query has changed.
// This is kind of an anti-pattern (props in state), but it works here
// since we know for sure that searchParameters having changed means a
// new search has been triggered.
if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) {
this.setState({
query: nextProps.currentRefinement
});
}
}
// From https://github.com/algolia/autocomplete.js/pull/86
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props;
var translate = _props.translate;
var autoFocus = _props.autoFocus;
var query = this.getQuery();
var submitComponent = this.props.submitComponent ? this.props.submitComponent : _react2.default.createElement(
'svg',
{ role: 'img' },
_react2.default.createElement('use', { xlinkHref: '#sbx-icon-search-13' })
);
var resetComponent = this.props.resetComponent ? this.props.resetComponent : _react2.default.createElement(
'svg',
{ role: 'img' },
_react2.default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' })
);
var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) {
if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) {
return _extends({}, props, _defineProperty({}, prop, _this2.props[prop]));
}
return props;
}, {});
/* eslint-disable max-len */
return _react2.default.createElement(
'form',
_extends({
noValidate: true,
onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit,
onReset: this.onReset
}, cx('root'), {
action: '',
role: 'search'
}),
_react2.default.createElement(
'svg',
{ xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } },
_react2.default.createElement(
'symbol',
{ xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-search-13', viewBox: '0 0 40 40' },
_react2.default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z',
fillRule: 'evenodd' })
),
_react2.default.createElement(
'symbol',
{ xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-clear-3', viewBox: '0 0 20 20' },
_react2.default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z', fillRule: 'evenodd' })
)
),
_react2.default.createElement(
'div',
_extends({
role: 'search'
}, cx('wrapper')),
_react2.default.createElement('input', _extends({
ref: this.onInputMount,
type: 'search',
placeholder: translate('placeholder'),
autoFocus: autoFocus,
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
spellCheck: 'false',
required: true,
value: query,
onChange: this.onChange
}, searchInputEvents, cx('input'))),
_react2.default.createElement(
'button',
_extends({ type: 'submit', title: translate('submitTitle') }, cx('submit')),
submitComponent
),
_react2.default.createElement(
'button',
_extends({ type: 'reset', title: translate('resetTitle') }, cx('reset'), { onClick: this.onReset }),
resetComponent
)
)
);
/* eslint-enable */
}
}]);
return SearchBox;
}(_react.Component);
SearchBox.propTypes = {
currentRefinement: _react.PropTypes.string,
refine: _react.PropTypes.func.isRequired,
translate: _react.PropTypes.func.isRequired,
resetComponent: _react.PropTypes.element,
submitComponent: _react.PropTypes.element,
focusShortcuts: _react.PropTypes.arrayOf(_react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number])),
autoFocus: _react.PropTypes.bool,
searchAsYouType: _react.PropTypes.bool,
onSubmit: _react.PropTypes.func,
onReset: _react.PropTypes.func,
onChange: _react.PropTypes.func,
// For testing purposes
__inputRef: _react.PropTypes.func
};
SearchBox.defaultProps = {
currentRefinement: '',
focusShortcuts: ['s', '/'],
autoFocus: false,
searchAsYouType: true
};
exports.default = (0, _translatable2.default)({
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(SearchBox);
/***/ }),
/* 343 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _has2 = __webpack_require__(37);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Select = function (_Component) {
_inherits(Select, _Component);
function Select() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Select);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.onSelect(e.target.value);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Select, [{
key: 'render',
value: function render() {
var _props = this.props;
var cx = _props.cx;
var items = _props.items;
var selectedItem = _props.selectedItem;
return _react2.default.createElement(
'select',
_extends({}, cx('root'), {
value: selectedItem,
onChange: this.onChange
}),
items.map(function (item) {
return _react2.default.createElement(
'option',
{
key: (0, _has3.default)(item, 'key') ? item.key : item.value,
disabled: item.disabled,
value: item.value
},
(0, _has3.default)(item, 'label') ? item.label : item.value
);
})
);
}
}]);
return Select;
}(_react.Component);
Select.propTypes = {
cx: _react.PropTypes.func.isRequired,
onSelect: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]).isRequired,
key: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]),
label: _react.PropTypes.string,
disabled: _react.PropTypes.bool
})).isRequired,
selectedItem: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]).isRequired
};
exports.default = Select;
/***/ }),
/* 344 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = buildSearchMethod;
var errors = __webpack_require__(211);
/**
* Creates a search method to be used in clients
* @param {string} queryParam the name of the attribute used for the query
* @param {string} url the url
* @return {function} the search method
*/
function buildSearchMethod(queryParam, url) {
/**
* The search method. Prepares the data and send the query to Algolia.
* @param {string} query the string used for query search
* @param {object} args additional parameters to send with the search
* @param {function} [callback] the callback to be called with the client gets the answer
* @return {undefined|Promise} If the callback is not provided then this methods returns a Promise
*/
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
// Normalizing the function signature
if (arguments.length === 0 || typeof query === 'function') {
// Usage : .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// Usage : .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// At this point we have 3 arguments with values
// Usage : .search(args) // careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
var additionalUA;
if (args !== undefined) {
if (args.additionalUA) {
additionalUA = args.additionalUA;
delete args.additionalUA;
}
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback, additionalUA);
};
}
/***/ }),
/* 345 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 346 */,
/* 347 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.default = createIndex;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Index = __webpack_require__(394);
var _Index2 = _interopRequireDefault(_Index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Creates a specialized root Index component. It accepts
* a specification of the root Element.
* @param {object} root - the defininition of the root of an Index sub tree.
* @returns {object} a Index root
*/
function createIndex(root) {
var _class, _temp;
return _temp = _class = function (_Component) {
_inherits(CreateIndex, _Component);
function CreateIndex() {
_classCallCheck(this, CreateIndex);
return _possibleConstructorReturn(this, (CreateIndex.__proto__ || Object.getPrototypeOf(CreateIndex)).apply(this, arguments));
}
_createClass(CreateIndex, [{
key: 'render',
value: function render() {
return _react2.default.createElement(_Index2.default, {
indexName: this.props.indexName,
root: root,
children: this.props.children
});
}
}]);
return CreateIndex;
}(_react.Component), _class.propTypes = {
children: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.arrayOf(_react2.default.PropTypes.node), _react2.default.PropTypes.node]),
indexName: _react.PropTypes.string.isRequired
}, _temp;
}
/***/ }),
/* 348 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.default = createInstantSearch;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _InstantSearch = __webpack_require__(395);
var _InstantSearch2 = _interopRequireDefault(_InstantSearch);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _name$author$descript = {
name: 'react-instantsearch',
author: {
name: 'Algolia, Inc.',
url: 'https://www.algolia.com'
},
description: '\u26A1 Lightning-fast search for React and React Native apps',
version: '4.0.0-beta.0',
scripts: {
build: './scripts/build.sh',
'build-and-publish': './scripts/build-and-publish.sh'
},
homepage: 'https://community.algolia.com/instantsearch.js/react/',
repository: {
type: 'git',
url: 'https://github.com/algolia/instantsearch.js/'
},
dependencies: {
algoliasearch: '^3.21.1',
'algoliasearch-helper': '2.19.0',
classnames: '^2.2.5',
lodash: '^4.17.4'
},
license: 'MIT',
devDependencies: {
enzyme: '^2.7.1',
react: '^15.4.2',
'react-dom': '^15.4.2',
'react-native': '^0.41.2',
'react-test-renderer': '^15.4.2'
}
};
var version = _name$author$descript.version;
/**
* Creates a specialized root InstantSearch component. It accepts
* an algolia client and a specification of the root Element.
* @param {function} defaultAlgoliaClient - a function that builds an Algolia client
* @param {object} root - the defininition of the root of an InstantSearch sub tree.
* @returns {object} an InstantSearch root
*/
function createInstantSearch(defaultAlgoliaClient, root) {
var _class, _temp;
return _temp = _class = function (_Component) {
_inherits(CreateInstantSearch, _Component);
function CreateInstantSearch(props) {
_classCallCheck(this, CreateInstantSearch);
var _this = _possibleConstructorReturn(this, (CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call(this));
_this.client = props.algoliaClient || defaultAlgoliaClient(props.appId, props.apiKey);
_this.client.addAlgoliaAgent('react-instantsearch ' + version);
return _this;
}
_createClass(CreateInstantSearch, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var props = this.props;
if (nextProps.algoliaClient) {
this.client = nextProps.algoliaClient;
} else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) {
this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey);
}
this.client.addAlgoliaAgent('react-instantsearch ' + version);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(_InstantSearch2.default, {
createURL: this.props.createURL,
indexName: this.props.indexName,
searchParameters: this.props.searchParameters,
searchState: this.props.searchState,
onSearchStateChange: this.props.onSearchStateChange,
root: root,
algoliaClient: this.client,
children: this.props.children
});
}
}]);
return CreateInstantSearch;
}(_react.Component), _class.propTypes = {
algoliaClient: _react.PropTypes.object,
appId: _react.PropTypes.string,
apiKey: _react.PropTypes.string,
children: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.arrayOf(_react2.default.PropTypes.node), _react2.default.PropTypes.node]),
indexName: _react.PropTypes.string.isRequired,
searchParameters: _react.PropTypes.object,
createURL: _react.PropTypes.func,
searchState: _react.PropTypes.object,
onSearchStateChange: _react.PropTypes.func
}, _temp;
}
/***/ }),
/* 349 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectCurrentRefinements = __webpack_require__(206);
var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements);
var _ClearAll = __webpack_require__(372);
var _ClearAll2 = _interopRequireDefault(_ClearAll);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The ClearAll widget displays a button that lets the user clean every refinement applied
* to the search.
* @name ClearAll
* @kind widget
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query
* @themeKey ais-ClearAll__root - the widget button
* @translationKey reset - the clear all button value
* @example
* import React from 'react';
*
* import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ClearAll />
* <RefinementList
attributeName="colors"
defaultRefinement={['Black']}
/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectCurrentRefinements2.default)(_ClearAll2.default);
/***/ }),
/* 350 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectConfigure = __webpack_require__(216);
var _connectConfigure2 = _interopRequireDefault(_connectConfigure);
var _Configure = __webpack_require__(373);
var _Configure2 = _interopRequireDefault(_Configure);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Configure is a widget that lets you provide raw search parameters
* to the Algolia API.
*
* Any of the props added to this widget will be forwarded to Algolia. For more information
* on the different parameters that can be set, have a look at the
* [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters).
*
* This widget can be used either with react-dom and react-native. It will not render anything
* on screen, only configure some parameters.
*
* Read more in the [Search parameters](guide/Search_parameters.html) guide.
* @name Configure
* @kind widget
* @example
* import React from 'react';
*
* import {Configure} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Configure distinct={1} />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectConfigure2.default)(_Configure2.default);
/***/ }),
/* 351 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectCurrentRefinements = __webpack_require__(206);
var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements);
var _CurrentRefinements = __webpack_require__(374);
var _CurrentRefinements2 = _interopRequireDefault(_CurrentRefinements);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The CurrentRefinements widget displays the list of currently applied filters.
*
* It allows the user to selectively remove them.
* @name CurrentRefinements
* @kind widget
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-CurrentRefinements__root - the root div of the widget
* @themeKey ais-CurrentRefinements__items - the container of the filters
* @themeKey ais-CurrentRefinements__item - a single filter
* @themeKey ais-CurrentRefinements__itemLabel - the label of a filter
* @themeKey ais-CurrentRefinements__itemClear - the trigger to remove the filter
* @themeKey ais-CurrentRefinements__noRefinement - present when there is no refinement
* @translationKey clearFilter - the remove filter button label
* @example
* import React from 'react';
*
* import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CurrentRefinements />
* <RefinementList
attributeName="colors"
defaultRefinement={['Black']}
/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectCurrentRefinements2.default)(_CurrentRefinements2.default);
/***/ }),
/* 352 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHierarchicalMenu = __webpack_require__(217);
var _connectHierarchicalMenu2 = _interopRequireDefault(_connectHierarchicalMenu);
var _HierarchicalMenu = __webpack_require__(375);
var _HierarchicalMenu2 = _interopRequireDefault(_HierarchicalMenu);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The hierarchical menu lets the user browse attributes using a tree-like structure.
*
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
*
* @name HierarchicalMenu
* @kind widget
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax.
* @propType {number} [limitMin=10] - The maximum number of items displayed.
* @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-HierarchicalMenu__root - Container of the widget
* @themeKey ais-HierarchicalMenu__items - Container of the items
* @themeKey ais-HierarchicalMenu__item - Id for a single list item
* @themeKey ais-HierarchicalMenu__itemSelected - Id for the selected items in the list
* @themeKey ais-HierarchicalMenu__itemParent - Id for the elements that have a sub list displayed
* @themeKey HierarchicalMenu__itemSelectedParent - Id for parents that have currently a child selected
* @themeKey ais-HierarchicalMenu__itemLink - the link containing the label and the count
* @themeKey ais-HierarchicalMenu__itemLabel - the label of the entry
* @themeKey ais-HierarchicalMenu__itemCount - the count of the entry
* @themeKey ais-HierarchicalMenu__itemItems - id representing a children
* @themeKey ais-HierarchicalMenu__showMore - container for the show more button
* @themeKey ais-HierarchicalMenu__noRefinement - present when there is no refinement
* @translationKey showMore - Label value of the button which toggles the number of items
* @example
* import React from 'react';
* import {
* InstantSearch,
* HierarchicalMenu,
* } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <HierarchicalMenu
* id="categories"
* key="categories"
* attributes={[
* 'category',
* 'sub_category',
* 'sub_sub_category',
* ]}
* />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHierarchicalMenu2.default)(_HierarchicalMenu2.default);
/***/ }),
/* 353 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHits = __webpack_require__(218);
var _connectHits2 = _interopRequireDefault(_connectHits);
var _Hits = __webpack_require__(377);
var _Hits2 = _interopRequireDefault(_Hits);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Displays a list of hits.
*
* To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html).
*
* @name Hits
* @kind widget
* @propType {Component} [hitComponent] - Component used for rendering each hit from
* the results. If it is not provided the rendering defaults to displaying the
* hit in its JSON form. The component will be called with a `hit` prop.
* @themeKey ais-Hits__root - the root of the component
* @example
* import React from 'react';
* import {
* InstantSearch,
* Hits,
* } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Hits />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHits2.default)(_Hits2.default);
/***/ }),
/* 354 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHitsPerPage = __webpack_require__(219);
var _connectHitsPerPage2 = _interopRequireDefault(_connectHitsPerPage);
var _HitsPerPage = __webpack_require__(378);
var _HitsPerPage2 = _interopRequireDefault(_HitsPerPage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The HitsPerPage widget displays a dropdown menu to let the user change the number
* of displayed hits.
*
* @name HitsPerPage
* @kind widget
* @propType {{value: number, label: string}[]} items - List of available options.
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-HitsPerPage__root - the root of the component.
* @example
* import React from 'react';
* import {
* InstantSearch,
* HitsPerPage,
* } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <HitsPerPage defaultRefinement={20}/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHitsPerPage2.default)(_HitsPerPage2.default);
/***/ }),
/* 355 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectInfiniteHits = __webpack_require__(220);
var _connectInfiniteHits2 = _interopRequireDefault(_connectInfiniteHits);
var _InfiniteHits = __webpack_require__(379);
var _InfiniteHits2 = _interopRequireDefault(_InfiniteHits);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Displays an infinite list of hits along with a **load more** button.
*
* To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html).
*
* @name InfiniteHits
* @kind widget
* @propType {Component} hitComponent - Component used for rendering each hit from
* the results. If it is not provided the rendering defaults to displaying the
* hit in its JSON form. The component will be called with a `hit` prop.
* @themeKey root - the root of the component
* @translationKey loadMore - the label of load more button
* @example
* import React from 'react';
* import {
* InstantSearch,
* Hits,
* } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <InfiniteHits />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectInfiniteHits2.default)(_InfiniteHits2.default);
/***/ }),
/* 356 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectMenu = __webpack_require__(221);
var _connectMenu2 = _interopRequireDefault(_connectMenu);
var _Menu = __webpack_require__(381);
var _Menu2 = _interopRequireDefault(_Menu);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Menu component displays a menu that lets the user choose a single value for a specific attribute.
* @name Menu
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of diplayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values
* @themeKey ais-Menu__root - the root of the component
* @themeKey ais-Menu__items - the container of all items in the menu
* @themeKey ais-Menu__item - a single item
* @themeKey ais-Menu__itemLinkSelected - the selected menu item
* @themeKey ais-Menu__itemLink - the item link
* @themeKey ais-Menu__itemLabelSelected - the selected item label
* @themeKey ais-Menu__itemLabel - the item label
* @themeKey ais-Menu__itemCount - the item count
* @themeKey ais-Menu__itemCountSelected - the selected item count
* @themeKey ais-Menu__noRefinement - present when there is no refinement
* @themeKey ais-Menu__showMore - the button that let the user toggle more results
* @themeKey ais-Menu__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded
* @translationkey noResults - The label of the no results text when no search for facet values results are found.
* @example
* import React from 'react';
*
* import {Menu, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Menu
* attributeName="category"
* />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectMenu2.default)(_Menu2.default);
/***/ }),
/* 357 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectMultiRange = __webpack_require__(222);
var _connectMultiRange2 = _interopRequireDefault(_connectMultiRange);
var _MultiRange = __webpack_require__(382);
var _MultiRange2 = _interopRequireDefault(_MultiRange);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* MultiRange is a widget used for selecting the range value of a numeric attribute.
* @name MultiRange
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max".
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-MultiRange__root - The root component of the widget
* @themeKey ais-MultiRange__items - The container of the items
* @themeKey ais-MultiRange__item - A single item
* @themeKey ais-MultiRange__itemSelected - The selected item
* @themeKey ais-MultiRange__itemLabel - The label of an item
* @themeKey ais-MultiRange__itemLabelSelected - The selected label item
* @themeKey ais-MultiRange__itemRadio - The radio of an item
* @themeKey ais-MultiRange__itemRadioSelected - The selected radio item
* @themeKey ais-MultiRange__noRefinement - present when there is no refinement for all ranges
* @themeKey ais-MultiRange__itemNoRefinement - present when there is no refinement for one range
* @themeKey ais-MultiRange__itemAll - indicate the range that will contain all the results
* @translationkey all - The label of the largest range added automatically by react instantsearch
* @example
* import React from 'react';
*
* import {InstantSearch, MultiRange} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <MultiRange attributeName="price"
* items={[
* {end: 10, label: '<$10'},
* {start: 10, end: 100, label: '$10-$100'},
* {start: 100, end: 500, label: '$100-$500'},
* {start: 500, label: '>$500'},
* ]}
* />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectMultiRange2.default)(_MultiRange2.default);
/***/ }),
/* 358 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectPagination = __webpack_require__(223);
var _connectPagination2 = _interopRequireDefault(_connectPagination);
var _Pagination = __webpack_require__(383);
var _Pagination2 = _interopRequireDefault(_Pagination);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Pagination widget displays a simple pagination system allowing the user to
* change the current page.
* @name Pagination
* @kind widget
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [pagesPadding=3] - How many page links to display around the current page.
* @propType {number} [maxPages=Infinity] - Maximum number of pages to display.
* @themeKey ais-Pagination__root - The root component of the widget
* @themeKey ais-Pagination__itemFirst - The first page link item
* @themeKey ais-Pagination__itemPrevious - The previous page link item
* @themeKey ais-Pagination__itemPage - The page link item
* @themeKey ais-Pagination__itemNext - The next page link item
* @themeKey ais-Pagination__itemLast - The last page link item
* @themeKey ais-Pagination__itemDisabled - a disabled item
* @themeKey ais-Pagination__itemSelected - a selected item
* @themeKey ais-Pagination__itemLink - The link of an item
* @themeKey ais-Pagination__noRefinement - present when there is no refinement
* @translationKey previous - Label value for the previous page link
* @translationKey next - Label value for the next page link
* @translationKey first - Label value for the first page link
* @translationKey last - Label value for the last page link
* @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string
* @translationKey ariaPrevious - Accessibility label value for the previous page link
* @translationKey ariaNext - Accessibility label value for the next page link
* @translationKey ariaFirst - Accessibility label value for the first page link
* @translationKey ariaLast - Accessibility label value for the last page link
* @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string
* @example
* import React from 'react';
*
* import {Pagination, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Pagination/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectPagination2.default)(_Pagination2.default);
/***/ }),
/* 359 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Panel = __webpack_require__(384);
var _Panel2 = _interopRequireDefault(_Panel);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Panel widget wraps other widgets in a consistent panel design.
*
* It also reacts, indicates and set CSS classes when widgets are no more
* relevant for refining. E.g. when a RefinementList becomes empty because of
* the current search results.
* @name Panel
* @kind widget
* @propType {string} title - The panel title
* @themeKey ais-Panel__root - Container of the widget
* @themeKey ais-Panel__title - The panel title
* @themeKey ais-Panel__noRefinement - Present if the panel content is empty
* @example
* import React from 'react';
*
* import {Panel, RefinementList, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Panel title="category">
* <RefinementList attributeName="category" />
* </Panel>
* </InstantSearch>
* );
* }
*/
exports.default = _Panel2.default;
/***/ }),
/* 360 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectPoweredBy = __webpack_require__(224);
var _connectPoweredBy2 = _interopRequireDefault(_connectPoweredBy);
var _PoweredBy = __webpack_require__(385);
var _PoweredBy2 = _interopRequireDefault(_PoweredBy);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* PoweredBy displays an Algolia logo.
*
* Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing).
* @name PoweredBy
* @kind widget
* @themeKey ais-PoweredBy__root - The root component of the widget
* @themeKey ais-PoweredBy__searchBy - The powered by label
* @themeKey ais-PoweredBy__algoliaLink - The algolia logo link
* @translationKey searchBy - Label value for the powered by
* @example
* import React from 'react';
*
* import {PoweredBy, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <PoweredBy />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectPoweredBy2.default)(_PoweredBy2.default);
/***/ }),
/* 361 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectRange = __webpack_require__(111);
var _connectRange2 = _interopRequireDefault(_connectRange);
var _RangeInput = __webpack_require__(386);
var _RangeInput2 = _interopRequireDefault(_RangeInput);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* RangeInput allows a user to select a numeric range using a minimum and maximum input.
* @name RangeInput
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @themeKey ais-RangeInput__root - The root component of the widget
* @themeKey ais-RangeInput__labelMin - The label for the min input
* @themeKey ais-RangeInput__inputMin - The min input
* @themeKey ais-RangeInput__separator - The separator between input
* @themeKey ais-RangeInput__labelMax - The label for the max input
* @themeKey ais-RangeInput__inputMax - The max input
* @themeKey ais-RangeInput__submit - The submit button
* @themeKey ais-RangeInput__noRefinement - present when there is no refinement
* @translationKey submit - Label value for the submit button
* @translationKey separator - Label value for the input separator
* @example
* import React from 'react';
*
* import {RangeInput, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RangeInput attributeName="price"/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectRange2.default)(_RangeInput2.default);
/***/ }),
/* 362 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectRange = __webpack_require__(111);
var _connectRange2 = _interopRequireDefault(_connectRange);
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Since a lot of sliders already exist, we did not include one by default.
* However you can easily connect React InstantSearch to an existing one
* using the [connectRange connector](connectors/connectRange.html).
*
* @name RangeSlider
* @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values.
* @kind widget
* @example
*
* // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the
* // range connector
*
* import React, {PropTypes} from 'react';
* import {connectRange} from 'react-instantsearch/connectors';
* import Rheostat from 'rheostat';
*
* const Range = React.createClass({
propTypes: {
min: React.PropTypes.number,
max: React.PropTypes.number,
currentRefinement: React.PropTypes.object,
refine: React.PropTypes.func.isRequired,
canRefine: React.PropTypes.bool.isRequired,
},
getInitialState() {
return {currentValues: {min: this.props.min, max: this.props.max}};
},
componentWillReceiveProps(sliderState) {
if (sliderState.canRefine) {
this.setState({currentValues: {min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max}});
}
},
onValuesUpdated(sliderState) {
this.setState({currentValues: {min: sliderState.values[0], max: sliderState.values[1]}});
},
onChange(sliderState) {
if (this.props.currentRefinement.min !== sliderState.values[0] ||
this.props.currentRefinement.max !== sliderState.values[1]) {
this.props.refine({min: sliderState.values[0], max: sliderState.values[1]});
}
},
render() {
const {min, max, currentRefinement} = this.props;
const {currentValues} = this.state;
return min !== max ?
<div>
<Rheostat
min={min}
max={max}
values={[currentRefinement.min, currentRefinement.max]}
onChange={this.onChange}
onValuesUpdated={this.onValuesUpdated}
/>
<div style={{display: 'flex', justifyContent: 'space-between'}}>
<div>{currentValues.min}</div>
<div>{currentValues.max}</div>
</div>
</div> : null;
},
});
const ConnectedRange = connectRange(Range);
*/
exports.default = (0, _connectRange2.default)(function () {
return _react2.default.createElement(
'div',
null,
'We do not provide any Slider, see the documentation to learn how to connect one easily:',
_react2.default.createElement(
'a',
{ target: '_blank', href: 'https://community.algolia.com/instantsearch.js/react/widgets/RangeSlider.html' },
'https://community.algolia.com/instantsearch.js/react/widgets/RangeSlider.html'
)
);
});
/***/ }),
/* 363 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectRefinementList = __webpack_require__(225);
var _connectRefinementList2 = _interopRequireDefault(_connectRefinementList);
var _RefinementList = __webpack_require__(387);
var _RefinementList2 = _interopRequireDefault(_RefinementList);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The RefinementList component displays a list that let the end user choose multiple values for a specific facet.
* @name RefinementList
* @kind widget
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of displayed items
* @propType {number} [limitMax=20] - the maximum number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} [defaultRefinement] - the values of the items selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-RefinementList__root - the root of the component
* @themeKey ais-RefinementList__items - the container of all items in the list
* @themeKey ais-RefinementList__itemSelected - the selected list item
* @themeKey ais-RefinementList__itemCheckbox - the item checkbox
* @themeKey ais-RefinementList__itemCheckboxSelected - the selected item checkbox
* @themeKey ais-RefinementList__itemLabel - the item label
* @themeKey ais-RefinementList__itemLabelSelected - the selected item label
* @themeKey RefinementList__itemCount - the item count
* @themeKey RefinementList__itemCountSelected - the selected item count
* @themeKey ais-RefinementList__showMore - the button that let the user toggle more results
* @themeKey ais-RefinementList__noRefinement - present when there is no refinement
* @themeKey ais-RefinementList__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded
* @translationkey noResults - The label of the no results text when no search for facet values results are found.
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @example
* import React from 'react';
*
* import {RefinementList, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RefinementList attributeName="colors" />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectRefinementList2.default)(_RefinementList2.default);
/***/ }),
/* 364 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectScrollTo = __webpack_require__(226);
var _connectScrollTo2 = _interopRequireDefault(_connectScrollTo);
var _ScrollTo = __webpack_require__(388);
var _ScrollTo2 = _interopRequireDefault(_ScrollTo);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The ScrollTo component will made the page scroll to the component wrapped by it when one of the
* [search state](guide/Search_state.html) prop is updated. By default when the page number changes,
* the scroll goes to the wrapped component.
*
* @name ScrollTo
* @kind widget
* @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes.
* @example
* import React from 'react';
*
* import {ScrollTo, Hits, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ScrollTo>
* <Hits />
* </ScrollTo>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectScrollTo2.default)(_ScrollTo2.default);
/***/ }),
/* 365 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectSearchBox = __webpack_require__(227);
var _connectSearchBox2 = _interopRequireDefault(_connectSearchBox);
var _SearchBox = __webpack_require__(342);
var _SearchBox2 = _interopRequireDefault(_SearchBox);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The SearchBox component displays a search box that lets the user search for a specific query.
* @name SearchBox
* @kind widget
* @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes.
* @propType {boolean} [autoFocus=false] - Should the search box be focused on render?
* @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused.
* @propType {function} [onSubmit] - Intercept submit event sent from the SearchBox form container.
* @propType {function} [onReset] - Listen to `reset` event sent from the SearchBox form container.
* @propType {function} [on*] - Listen to any events sent form the search input itself.
* @propType {React.Element} [submitComponent] - Change the apparence of the default submit button (magnifying glass).
* @propType {React.Element} [resetComponent] - Change the apparence of the default reset button (cross).
* @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted.
* @themeKey ais-SearchBox__root - the root of the component
* @themeKey ais-SearchBox__wrapper - the search box wrapper
* @themeKey ais-SearchBox__input - the search box input
* @themeKey ais-SearchBox__submit - the submit button
* @themeKey ais-SearchBox__reset - the reset button
* @translationkey submitTitle - The submit button title
* @translationkey resetTitle - The reset button title
* @translationkey placeholder - The label of the input placeholder
* @example
* import React from 'react';
*
* import {SearchBox, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SearchBox />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectSearchBox2.default)(_SearchBox2.default);
/***/ }),
/* 366 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHighlight = __webpack_require__(207);
var _connectHighlight2 = _interopRequireDefault(_connectHighlight);
var _Snippet = __webpack_require__(389);
var _Snippet2 = _interopRequireDefault(_Snippet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Renders any attribute from an hit into its highlighted snippet form when relevant.
*
* Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide.
* @name Snippet
* @kind widget
* @propType {string} attributeName - the location of the highlighted snippet attribute in the hit
* @propType {object} hit - the hit object containing the highlighted snippet attribute
* @example
* import React from 'react';
*
* import {InstantSearch, connectHits, Snippet} from 'InstantSearch';
*
* const CustomHits = connectHits(hits => {
* return hits.map((hit) => <p><Snippet attributeName="description" hit={hit}/></p>);
* });
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CustomHits />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHighlight2.default)(_Snippet2.default);
/***/ }),
/* 367 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectSortBy = __webpack_require__(228);
var _connectSortBy2 = _interopRequireDefault(_connectSortBy);
var _SortBy = __webpack_require__(390);
var _SortBy2 = _interopRequireDefault(_SortBy);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The SortBy component displays a list of indexes allowing a user to change the hits are sorting.
* @name SortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind widget
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {string} defaultRefinement - The default selected index.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-SortBy__root - the root of the component
* @example
* import React from 'react';
*
* import {SortBy, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SortBy
* items={[
* {value: 'ikea', label: 'Featured'},
* {value: 'ikea_price_asc', label: 'Price asc.'},
* {value: 'ikea_price_desc', label: 'Price desc.'},
* ]}
* defaultRefinement="ikea"
* />
* </InstantSearch>
* );
* } */
exports.default = (0, _connectSortBy2.default)(_SortBy2.default);
/***/ }),
/* 368 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectRange = __webpack_require__(111);
var _connectRange2 = _interopRequireDefault(_connectRange);
var _StarRating = __webpack_require__(391);
var _StarRating2 = _interopRequireDefault(_StarRating);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* StarRating lets the user refine search results by clicking on stars.
*
* The stars are based on the selected `attributeName`.
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @name StarRating
* @kind widget
* @propType {string} attributeName - the name of the attribute in the record
* @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating.
* @themeKey ais-StarRating__root - The root component of the widget
* @themeKey ais-StarRating__ratingLink - The item link
* @themeKey ais-StarRating__ratingLinkSelected - The selected link item
* @themeKey ais-StarRating__ratingLinkDisabled - The disabled link item
* @themeKey ais-StarRating__ratingIcon - The rating icon
* @themeKey ais-StarRating__ratingIconSelected - The selected rating icon
* @themeKey ais-StarRating__ratingIconDisabled - The disabled rating icon
* @themeKey ais-StarRating__ratingIconEmpty - The rating empty icon
* @themeKey ais-StarRating__ratingIconEmptySelected - The selected rating empty icon
* @themeKey ais-StarRating__ratingIconEmptyDisabled - The disabled rating empty icon
* @themeKey ais-StarRating__ratingLabel - The link label
* @themeKey ais-StarRating__ratingLabelSelected - The selected link label
* @themeKey ais-StarRating__ratingLabelDisabled - The disabled link label
* @themeKey ais-StarRating__ratingCount - The link count
* @themeKey ais-StarRating__ratingCountSelected - The selected link count
* @themeKey ais-StarRating__ratingCountDisabled - The disabled link count
* @themeKey ais-StarRating__noRefinement - present when there is no refinement
* @translationKey ratingLabel - Label value for the rating link
* @example
* import React from 'react';
*
* import {StarRating, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <StarRating attributeName="rating" />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectRange2.default)(_StarRating2.default);
/***/ }),
/* 369 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectStats = __webpack_require__(229);
var _connectStats2 = _interopRequireDefault(_connectStats);
var _Stats = __webpack_require__(392);
var _Stats2 = _interopRequireDefault(_Stats);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server).
* @name Stats
* @kind widget
* @themeKey ais-Stats__root - the root of the component
* @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time.
* @example
* import React from 'react';
*
* import {Stats, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Stats />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectStats2.default)(_Stats2.default);
/***/ }),
/* 370 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectToggle = __webpack_require__(230);
var _connectToggle2 = _interopRequireDefault(_connectToggle);
var _Toggle = __webpack_require__(393);
var _Toggle2 = _interopRequireDefault(_Toggle);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Toggle provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization.
* @name Toggle
* @kind widget
* @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attributeName` when checked.
* @propType {boolean} [defaultChecked=false] - Default state of the widget. Should the toggle be checked by default?
* @themeKey ais-Toggle__root - the root of the component
* @themeKey ais-Toggle__checkbox - the toggle checkbox
* @themeKey ais-Toggle__label - the toggle label
* @example
* import React from 'react';
*
* import {Toggle, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Toggle attributeName="materials"
* label="Made with solid pine"
* value={'Solid pine'}
* />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectToggle2.default)(_Toggle2.default);
/***/ }),
/* 371 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var AlgoliaSearchCore = __webpack_require__(400);
var createAlgoliasearch = __webpack_require__(402);
module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) ');
/***/ }),
/* 372 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('ClearAll');
var ClearAll = function (_Component) {
_inherits(ClearAll, _Component);
function ClearAll() {
_classCallCheck(this, ClearAll);
return _possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments));
}
_createClass(ClearAll, [{
key: 'render',
value: function render() {
var _props = this.props;
var translate = _props.translate;
var items = _props.items;
var refine = _props.refine;
var isDisabled = items.length === 0;
if (isDisabled) {
return _react2.default.createElement(
'button',
_extends({}, cx('root'), { disabled: true }),
translate('reset')
);
}
return _react2.default.createElement(
'button',
_extends({}, cx('root'), {
onClick: refine.bind(null, items)
}),
translate('reset')
);
}
}]);
return ClearAll;
}(_react.Component);
ClearAll.propTypes = {
translate: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.object).isRequired,
refine: _react.PropTypes.func.isRequired
};
exports.default = (0, _translatable2.default)({
reset: 'Clear all filters'
})(ClearAll);
/***/ }),
/* 373 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
return null;
};
/***/ }),
/* 374 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('CurrentRefinements');
var CurrentRefinements = function (_Component) {
_inherits(CurrentRefinements, _Component);
function CurrentRefinements() {
_classCallCheck(this, CurrentRefinements);
return _possibleConstructorReturn(this, (CurrentRefinements.__proto__ || Object.getPrototypeOf(CurrentRefinements)).apply(this, arguments));
}
_createClass(CurrentRefinements, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var translate = _props.translate;
var items = _props.items;
var refine = _props.refine;
var canRefine = _props.canRefine;
return _react2.default.createElement(
'div',
cx('root', !canRefine && 'noRefinement'),
_react2.default.createElement(
'div',
cx('items'),
items.map(function (item) {
return _react2.default.createElement(
'div',
_extends({
key: item.label
}, cx('item', item.items && 'itemParent')),
_react2.default.createElement(
'span',
cx('itemLabel'),
item.label
),
item.items ? item.items.map(function (nestedItem) {
return _react2.default.createElement(
'div',
_extends({
key: nestedItem.label
}, cx('item')),
_react2.default.createElement(
'span',
cx('itemLabel'),
nestedItem.label
),
_react2.default.createElement(
'button',
_extends({}, cx('itemClear'), {
onClick: refine.bind(null, nestedItem.value)
}),
translate('clearFilter', nestedItem)
)
);
}) : _react2.default.createElement(
'button',
_extends({}, cx('itemClear'), {
onClick: refine.bind(null, item.value)
}),
translate('clearFilter', item)
)
);
})
)
);
}
}]);
return CurrentRefinements;
}(_react.Component);
CurrentRefinements.propTypes = {
translate: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string
})).isRequired,
refine: _react.PropTypes.func.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
transformItems: _react.PropTypes.func
};
CurrentRefinements.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
clearFilter: '✕'
})(CurrentRefinements);
/***/ }),
/* 375 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _pick2 = __webpack_require__(110);
var _pick3 = _interopRequireDefault(_pick2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _List = __webpack_require__(208);
var _List2 = _interopRequireDefault(_List);
var _Link = __webpack_require__(232);
var _Link2 = _interopRequireDefault(_Link);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('HierarchicalMenu');
var itemsPropType = _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string.isRequired,
value: _react.PropTypes.string,
count: _react.PropTypes.number.isRequired,
items: function items() {
return itemsPropType.apply(undefined, arguments);
}
}));
var HierarchicalMenu = function (_Component) {
_inherits(HierarchicalMenu, _Component);
function HierarchicalMenu() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, HierarchicalMenu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props;
var createURL = _this$props.createURL;
var refine = _this$props.refine;
return _react2.default.createElement(
_Link2.default,
_extends({}, cx('itemLink'), {
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
}),
_react2.default.createElement(
'span',
cx('itemLabel'),
item.label
),
' ',
_react2.default.createElement(
'span',
cx('itemCount'),
item.count
)
);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(HierarchicalMenu, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(_List2.default, _extends({
renderItem: this.renderItem,
cx: cx
}, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isEmpty', 'canRefine'])));
}
}]);
return HierarchicalMenu;
}(_react.Component);
HierarchicalMenu.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
createURL: _react.PropTypes.func.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
items: itemsPropType,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
transformItems: _react.PropTypes.func
};
HierarchicalMenu.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
}
})(HierarchicalMenu);
/***/ }),
/* 376 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = Highlight;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Highlighter = __webpack_require__(341);
var _Highlighter2 = _interopRequireDefault(_Highlighter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Highlight(props) {
return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_highlightResult' }, props));
}
Highlight.propTypes = {
hit: _react2.default.PropTypes.object.isRequired,
attributeName: _react2.default.PropTypes.string.isRequired,
highlight: _react2.default.PropTypes.func.isRequired
};
/***/ }),
/* 377 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Hits');
var Hits = function (_Component) {
_inherits(Hits, _Component);
function Hits() {
_classCallCheck(this, Hits);
return _possibleConstructorReturn(this, (Hits.__proto__ || Object.getPrototypeOf(Hits)).apply(this, arguments));
}
_createClass(Hits, [{
key: 'render',
value: function render() {
var _props = this.props;
var ItemComponent = _props.hitComponent;
var hits = _props.hits;
return _react2.default.createElement(
'div',
cx('root'),
hits.map(function (hit) {
return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit });
})
);
}
}]);
return Hits;
}(_react.Component);
Hits.propTypes = {
hits: _react.PropTypes.array,
hitComponent: _react.PropTypes.func.isRequired
};
Hits.defaultProps = {
hitComponent: function hitComponent(hit) {
return _react2.default.createElement(
'div',
{
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px'
}
},
JSON.stringify(hit).slice(0, 100),
'...'
);
}
};
exports.default = Hits;
/***/ }),
/* 378 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Select = __webpack_require__(343);
var _Select2 = _interopRequireDefault(_Select);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('HitsPerPage');
var HitsPerPage = function (_Component) {
_inherits(HitsPerPage, _Component);
function HitsPerPage() {
_classCallCheck(this, HitsPerPage);
return _possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments));
}
_createClass(HitsPerPage, [{
key: 'render',
value: function render() {
var _props = this.props;
var currentRefinement = _props.currentRefinement;
var refine = _props.refine;
var items = _props.items;
return _react2.default.createElement(_Select2.default, {
onSelect: refine,
selectedItem: currentRefinement,
items: items,
cx: cx
});
}
}]);
return HitsPerPage;
}(_react.Component);
HitsPerPage.propTypes = {
refine: _react.PropTypes.func.isRequired,
currentRefinement: _react.PropTypes.number.isRequired,
transformItems: _react.PropTypes.func,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
/**
* Number of hits to display.
*/
value: _react.PropTypes.number.isRequired,
/**
* Label to display on the option.
*/
label: _react.PropTypes.string
}))
};
exports.default = HitsPerPage;
/***/ }),
/* 379 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('InfiniteHits');
var InfiniteHits = function (_Component) {
_inherits(InfiniteHits, _Component);
function InfiniteHits() {
_classCallCheck(this, InfiniteHits);
return _possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments));
}
_createClass(InfiniteHits, [{
key: 'render',
value: function render() {
var _props = this.props;
var ItemComponent = _props.hitComponent;
var hits = _props.hits;
var hasMore = _props.hasMore;
var refine = _props.refine;
var translate = _props.translate;
var renderedHits = hits.map(function (hit) {
return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit });
});
var loadMoreButton = hasMore ? _react2.default.createElement(
'button',
_extends({}, cx('loadMore'), { onClick: function onClick() {
return refine();
} }),
translate('loadMore')
) : _react2.default.createElement(
'button',
_extends({}, cx('loadMore'), { disabled: true }),
translate('loadMore')
);
return _react2.default.createElement(
'div',
cx('root'),
renderedHits,
loadMoreButton
);
}
}]);
return InfiniteHits;
}(_react.Component);
InfiniteHits.propTypes = {
hits: _react.PropTypes.array,
hitComponent: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]).isRequired,
hasMore: _react.PropTypes.bool.isRequired,
refine: _react.PropTypes.func.isRequired,
translate: _react.PropTypes.func.isRequired
};
InfiniteHits.defaultProps = {
hitComponent: function hitComponent(hit) {
return _react2.default.createElement(
'div',
{
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px'
}
},
JSON.stringify(hit).slice(0, 100),
'...'
);
}
};
exports.default = (0, _translatable2.default)({
loadMore: 'Load more'
})(InfiniteHits);
/***/ }),
/* 380 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _has2 = __webpack_require__(37);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Link = __webpack_require__(232);
var _Link2 = _interopRequireDefault(_Link);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var LinkList = function (_Component) {
_inherits(LinkList, _Component);
function LinkList() {
_classCallCheck(this, LinkList);
return _possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments));
}
_createClass(LinkList, [{
key: 'render',
value: function render() {
var _props = this.props;
var cx = _props.cx;
var createURL = _props.createURL;
var items = _props.items;
var onSelect = _props.onSelect;
var canRefine = _props.canRefine;
return _react2.default.createElement(
'ul',
cx('root', !canRefine && 'noRefinement'),
items.map(function (item) {
return _react2.default.createElement(
'li',
_extends({
key: (0, _has3.default)(item, 'key') ? item.key : item.value
}, cx('item', item.selected && !item.disabled && 'itemSelected', item.disabled && 'itemDisabled', item.modifier), {
disabled: item.disabled
}),
item.disabled ? _react2.default.createElement(
'span',
cx('itemLink', 'itemLinkDisabled'),
(0, _has3.default)(item, 'label') ? item.label : item.value
) : _react2.default.createElement(
_Link2.default,
_extends({}, cx('itemLink', item.selected && 'itemLinkSelected'), {
'aria-label': item.ariaLabel,
href: createURL(item.value),
onClick: onSelect.bind(null, item.value)
}),
(0, _has3.default)(item, 'label') ? item.label : item.value
)
);
})
);
}
}]);
return LinkList;
}(_react.Component);
LinkList.propTypes = {
cx: _react.PropTypes.func.isRequired,
createURL: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number, _react.PropTypes.object]).isRequired,
key: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]),
label: _react.PropTypes.node,
modifier: _react.PropTypes.string,
ariaLabel: _react.PropTypes.string,
disabled: _react.PropTypes.bool
})),
onSelect: _react.PropTypes.func.isRequired,
canRefine: _react.PropTypes.bool.isRequired
};
exports.default = LinkList;
/***/ }),
/* 381 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _pick2 = __webpack_require__(110);
var _pick3 = _interopRequireDefault(_pick2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _List = __webpack_require__(208);
var _List2 = _interopRequireDefault(_List);
var _Link = __webpack_require__(232);
var _Link2 = _interopRequireDefault(_Link);
var _Highlight = __webpack_require__(231);
var _Highlight2 = _interopRequireDefault(_Highlight);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Menu');
var Menu = function (_Component) {
_inherits(Menu, _Component);
function Menu() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Menu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props;
var refine = _this$props.refine;
var createURL = _this$props.createURL;
var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label;
return _react2.default.createElement(
_Link2.default,
_extends({}, cx('itemLink', item.isRefined && 'itemLinkSelected'), {
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
}),
_react2.default.createElement(
'span',
cx('itemLabel', item.isRefined && 'itemLabelSelected'),
label
),
' ',
_react2.default.createElement(
'span',
cx('itemCount', item.isRefined && 'itemCountSelected'),
item.count
)
);
}, _this.selectItem = function (item) {
_this.props.refine(item.value);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Menu, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(_List2.default, _extends({
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx
}, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine'])));
}
}]);
return Menu;
}(_react.Component);
Menu.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
searchForItems: _react.PropTypes.func.isRequired,
withSearchBox: _react.PropTypes.bool,
createURL: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string.isRequired,
value: _react.PropTypes.string.isRequired,
count: _react.PropTypes.number.isRequired,
isRefined: _react.PropTypes.bool.isRequired
})),
isFromSearch: _react.PropTypes.bool.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
transformItems: _react.PropTypes.func
};
Menu.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
},
noResults: 'No results',
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(Menu);
/***/ }),
/* 382 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _List = __webpack_require__(208);
var _List2 = _interopRequireDefault(_List);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('MultiRange');
var MultiRange = function (_Component) {
_inherits(MultiRange, _Component);
function MultiRange() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, MultiRange);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MultiRange.__proto__ || Object.getPrototypeOf(MultiRange)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props;
var refine = _this$props.refine;
var translate = _this$props.translate;
var label = item.value === '' ? translate('all') : item.label;
return _react2.default.createElement(
'label',
cx(item.value === '' && 'itemAll'),
_react2.default.createElement('input', _extends({}, cx('itemRadio', item.isRefined && 'itemRadioSelected'), {
type: 'radio',
checked: item.isRefined,
disabled: item.noRefinement,
onChange: refine.bind(null, item.value)
})),
_react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')),
_react2.default.createElement(
'span',
cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'),
label
)
);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(MultiRange, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var items = _props.items;
var canRefine = _props.canRefine;
return _react2.default.createElement(_List2.default, {
renderItem: this.renderItem,
showMore: false,
canRefine: canRefine,
cx: cx,
items: items.map(function (item) {
return _extends({}, item, { key: item.value });
})
});
}
}]);
return MultiRange;
}(_react.Component);
MultiRange.propTypes = {
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.node.isRequired,
value: _react.PropTypes.string.isRequired,
isRefined: _react.PropTypes.bool.isRequired,
noRefinement: _react.PropTypes.bool.isRequired
})).isRequired,
refine: _react.PropTypes.func.isRequired,
transformItems: _react.PropTypes.func,
canRefine: _react.PropTypes.bool.isRequired,
translate: _react.PropTypes.func.isRequired
};
MultiRange.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
all: 'All'
})(MultiRange);
/***/ }),
/* 383 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _range2 = __webpack_require__(420);
var _range3 = _interopRequireDefault(_range2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(56);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _LinkList = __webpack_require__(380);
var _LinkList2 = _interopRequireDefault(_LinkList);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Pagination');
function getPagesDisplayedCount(padding, total) {
return Math.min(2 * padding + 1, total);
}
function calculatePaddingLeft(current, padding, total, totalDisplayedPages) {
if (current <= padding) {
return current;
}
if (current >= total - padding) {
return totalDisplayedPages - (total - current);
}
return padding;
}
function getPages(page, total, padding) {
var totalDisplayedPages = getPagesDisplayedCount(padding, total);
if (totalDisplayedPages === total) return (0, _range3.default)(1, total + 1);
var paddingLeft = calculatePaddingLeft(page, padding, total, totalDisplayedPages);
var paddingRight = totalDisplayedPages - paddingLeft;
var first = page - paddingLeft;
var last = page + paddingRight;
return (0, _range3.default)(first + 1, last + 1);
}
var Pagination = function (_Component) {
_inherits(Pagination, _Component);
function Pagination() {
_classCallCheck(this, Pagination);
return _possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments));
}
_createClass(Pagination, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'getItem',
value: function getItem(modifier, translationKey, value) {
var _props = this.props;
var nbPages = _props.nbPages;
var maxPages = _props.maxPages;
var translate = _props.translate;
return {
key: modifier + '.' + value,
modifier: modifier,
disabled: value < 1 || value >= Math.min(maxPages, nbPages),
label: translate(translationKey, value),
value: value,
ariaLabel: translate('aria' + (0, _utils.capitalize)(translationKey), value)
};
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props;
var nbPages = _props2.nbPages;
var maxPages = _props2.maxPages;
var currentRefinement = _props2.currentRefinement;
var pagesPadding = _props2.pagesPadding;
var showFirst = _props2.showFirst;
var showPrevious = _props2.showPrevious;
var showNext = _props2.showNext;
var showLast = _props2.showLast;
var refine = _props2.refine;
var createURL = _props2.createURL;
var translate = _props2.translate;
var ListComponent = _props2.listComponent;
var otherProps = _objectWithoutProperties(_props2, ['nbPages', 'maxPages', 'currentRefinement', 'pagesPadding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'translate', 'listComponent']);
var totalPages = Math.min(nbPages, maxPages);
var lastPage = totalPages;
var items = [];
if (showFirst) {
items.push({
key: 'first',
modifier: 'itemFirst',
disabled: currentRefinement === 1,
label: translate('first'),
value: 1,
ariaLabel: translate('ariaFirst')
});
}
if (showPrevious) {
items.push({
key: 'previous',
modifier: 'itemPrevious',
disabled: currentRefinement === 1,
label: translate('previous'),
value: currentRefinement - 1,
ariaLabel: translate('ariaPrevious')
});
}
items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) {
return {
key: value,
modifier: 'itemPage',
label: translate('page', value),
value: value,
selected: value === currentRefinement,
ariaLabel: translate('ariaPage', value)
};
}));
if (showNext) {
items.push({
key: 'next',
modifier: 'itemNext',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('next'),
value: currentRefinement + 1,
ariaLabel: translate('ariaNext')
});
}
if (showLast) {
items.push({
key: 'last',
modifier: 'itemLast',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('last'),
value: lastPage,
ariaLabel: translate('ariaLast')
});
}
return _react2.default.createElement(ListComponent, _extends({}, otherProps, {
cx: cx,
items: items,
onSelect: refine,
createURL: createURL
}));
}
}]);
return Pagination;
}(_react.Component);
Pagination.propTypes = {
nbPages: _react.PropTypes.number.isRequired,
currentRefinement: _react.PropTypes.number.isRequired,
refine: _react.PropTypes.func.isRequired,
createURL: _react.PropTypes.func.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
translate: _react.PropTypes.func.isRequired,
listComponent: _react.PropTypes.func,
showFirst: _react.PropTypes.bool,
showPrevious: _react.PropTypes.bool,
showNext: _react.PropTypes.bool,
showLast: _react.PropTypes.bool,
pagesPadding: _react.PropTypes.number,
maxPages: _react.PropTypes.number
};
Pagination.defaultProps = {
listComponent: _LinkList2.default,
showFirst: true,
showPrevious: true,
showNext: true,
showLast: false,
pagesPadding: 3,
maxPages: Infinity
};
Pagination.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
previous: '‹',
next: '›',
first: '«',
last: '»',
page: function page(currentRefinement) {
return currentRefinement.toString();
},
ariaPrevious: 'Previous page',
ariaNext: 'Next page',
ariaFirst: 'First page',
ariaLast: 'Last page',
ariaPage: function ariaPage(currentRefinement) {
return 'Page ' + currentRefinement.toString();
}
})(Pagination);
/***/ }),
/* 384 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Panel');
var Panel = function (_Component) {
_inherits(Panel, _Component);
_createClass(Panel, [{
key: 'getChildContext',
value: function getChildContext() {
return { canRefine: this.canRefine };
}
}]);
function Panel(props) {
_classCallCheck(this, Panel);
var _this = _possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props));
_this.state = { canRefine: true };
_this.canRefine = function (canRefine) {
_this.setState({ canRefine: canRefine });
};
return _this;
}
_createClass(Panel, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
cx('root', !this.state.canRefine && 'noRefinement'),
_react2.default.createElement(
'h5',
cx('title'),
this.props.title
),
this.props.children
);
}
}]);
return Panel;
}(_react.Component);
Panel.propTypes = {
title: _react.PropTypes.string.isRequired,
children: _react.PropTypes.node
};
Panel.childContextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = Panel;
/***/ }),
/* 385 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('PoweredBy');
/* eslint-disable max-len */
var AlgoliaLogo = function AlgoliaLogo() {
return _react2.default.createElement(
'svg',
{ xmlns: 'http://www.w3.org/2000/svg', baseProfile: 'basic', viewBox: '0 0 1366 362' },
_react2.default.createElement(
'linearGradient',
{ id: 'g', x1: '428.258', x2: '434.145', y1: '404.15', y2: '409.85', gradientUnits: 'userSpaceOnUse', gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)' },
_react2.default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }),
_react2.default.createElement('stop', { offset: '1', stopColor: '#3369E7' })
),
_react2.default.createElement('path', { d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z', fill: 'url(#g)' }),
_react2.default.createElement('path', { d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z', fill: '#FFFFFF' }),
_react2.default.createElement('path', { d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z', fill: '#182359' })
);
};
/* eslint-enable max-len */
var PoweredBy = function (_Component) {
_inherits(PoweredBy, _Component);
function PoweredBy() {
_classCallCheck(this, PoweredBy);
return _possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments));
}
_createClass(PoweredBy, [{
key: 'render',
value: function render() {
var _props = this.props;
var translate = _props.translate;
var url = _props.url;
return _react2.default.createElement(
'div',
cx('root'),
_react2.default.createElement(
'span',
cx('searchBy'),
translate('searchBy'),
' '
),
_react2.default.createElement(
'a',
_extends({ href: url, target: '_blank' }, cx('algoliaLink')),
_react2.default.createElement(AlgoliaLogo, null)
)
);
}
}]);
return PoweredBy;
}(_react.Component);
PoweredBy.propTypes = {
url: _react.PropTypes.string.isRequired,
translate: _react.PropTypes.func.isRequired
};
exports.default = (0, _translatable2.default)({
searchBy: 'Search by'
})(PoweredBy);
/***/ }),
/* 386 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isNaN2 = __webpack_require__(214);
var _isNaN3 = _interopRequireDefault(_isNaN2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('RangeInput');
var RangeInput = function (_Component) {
_inherits(RangeInput, _Component);
function RangeInput(props) {
_classCallCheck(this, RangeInput);
var _this = _possibleConstructorReturn(this, (RangeInput.__proto__ || Object.getPrototypeOf(RangeInput)).call(this, props));
_this.onSubmit = function (e) {
e.preventDefault();
e.stopPropagation();
if (!(0, _isNaN3.default)(parseFloat(_this.state.from, 10)) && !(0, _isNaN3.default)(parseFloat(_this.state.to, 10))) {
_this.props.refine({ min: _this.state.from, max: _this.state.to });
}
};
_this.state = _this.props.canRefine ? { from: props.currentRefinement.min, to: props.currentRefinement.max } : { from: '', to: '' };
return _this;
}
_createClass(RangeInput, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (nextProps.canRefine) {
this.setState({ from: nextProps.currentRefinement.min, to: nextProps.currentRefinement.max });
}
if (this.context.canRefine) this.context.canRefine(nextProps.canRefine);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props;
var translate = _props.translate;
var canRefine = _props.canRefine;
return _react2.default.createElement(
'form',
_extends({}, cx('root', !canRefine && 'noRefinement'), { onSubmit: this.onSubmit }),
_react2.default.createElement(
'fieldset',
_extends({ disabled: !canRefine }, cx('fieldset')),
_react2.default.createElement(
'label',
cx('labelMin'),
_react2.default.createElement('input', _extends({}, cx('inputMin'), {
type: 'number', value: this.state.from, onChange: function onChange(e) {
return _this2.setState({ from: e.target.value });
}
}))
),
_react2.default.createElement(
'span',
cx('separator'),
translate('separator')
),
_react2.default.createElement(
'label',
cx('labelMax'),
_react2.default.createElement('input', _extends({}, cx('inputMax'), {
type: 'number', value: this.state.to, onChange: function onChange(e) {
return _this2.setState({ to: e.target.value });
}
}))
),
_react2.default.createElement(
'button',
_extends({}, cx('submit'), { type: 'submit' }),
translate('submit')
)
)
);
}
}]);
return RangeInput;
}(_react.Component);
RangeInput.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
min: _react.PropTypes.number,
max: _react.PropTypes.number,
currentRefinement: _react.PropTypes.shape({
min: _react.PropTypes.number,
max: _react.PropTypes.number
}),
canRefine: _react.PropTypes.bool.isRequired
};
RangeInput.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
submit: 'ok',
separator: 'to'
})(RangeInput);
/***/ }),
/* 387 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _pick2 = __webpack_require__(110);
var _pick3 = _interopRequireDefault(_pick2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _List = __webpack_require__(208);
var _List2 = _interopRequireDefault(_List);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
var _Highlight = __webpack_require__(231);
var _Highlight2 = _interopRequireDefault(_Highlight);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('RefinementList');
var RefinementList = function (_Component) {
_inherits(RefinementList, _Component);
function RefinementList(props) {
_classCallCheck(this, RefinementList);
var _this = _possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props));
_this.selectItem = function (item) {
_this.props.refine(item.value);
};
_this.renderItem = function (item) {
var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label;
return _react2.default.createElement(
'label',
null,
_react2.default.createElement('input', _extends({}, cx('itemCheckbox', item.isRefined && 'itemCheckboxSelected'), {
type: 'checkbox',
checked: item.isRefined,
onChange: function onChange() {
return _this.selectItem(item);
}
})),
_react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')),
_react2.default.createElement(
'span',
cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'),
label
),
' ',
_react2.default.createElement(
'span',
cx('itemCount', item.isRefined && 'itemCountSelected'),
item.count
)
);
};
_this.state = { query: '' };
return _this;
}
_createClass(RefinementList, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(_List2.default, _extends({
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx
}, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine'])))
);
}
}]);
return RefinementList;
}(_react.Component);
RefinementList.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
searchForItems: _react.PropTypes.func.isRequired,
withSearchBox: _react.PropTypes.bool,
createURL: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string.isRequired,
value: _react.PropTypes.arrayOf(_react.PropTypes.string).isRequired,
count: _react.PropTypes.number.isRequired,
isRefined: _react.PropTypes.bool.isRequired
})),
isFromSearch: _react.PropTypes.bool.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
transformItems: _react.PropTypes.func
};
RefinementList.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
},
noResults: 'No results',
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(RefinementList);
/***/ }),
/* 388 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _reactDom = __webpack_require__(425);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ScrollTo = function (_Component) {
_inherits(ScrollTo, _Component);
function ScrollTo() {
_classCallCheck(this, ScrollTo);
return _possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments));
}
_createClass(ScrollTo, [{
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
var value = this.props.value;
if (value !== prevProps.value) {
var el = (0, _reactDom.findDOMNode)(this);
el.scrollIntoView();
}
}
}, {
key: 'render',
value: function render() {
return _react.Children.only(this.props.children);
}
}]);
return ScrollTo;
}(_react.Component);
ScrollTo.propTypes = {
value: _react.PropTypes.any,
children: _react.PropTypes.node
};
exports.default = ScrollTo;
/***/ }),
/* 389 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = Snippet;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Highlighter = __webpack_require__(341);
var _Highlighter2 = _interopRequireDefault(_Highlighter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Snippet(props) {
return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_snippetResult' }, props));
}
Snippet.propTypes = {
hit: _react2.default.PropTypes.object.isRequired,
attributeName: _react2.default.PropTypes.string.isRequired,
highlight: _react2.default.PropTypes.func.isRequired
};
/***/ }),
/* 390 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Select = __webpack_require__(343);
var _Select2 = _interopRequireDefault(_Select);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('SortBy');
var SortBy = function (_Component) {
_inherits(SortBy, _Component);
function SortBy() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, SortBy);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = SortBy.__proto__ || Object.getPrototypeOf(SortBy)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.refine(e.target.value);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(SortBy, [{
key: 'render',
value: function render() {
var _props = this.props;
var refine = _props.refine;
var items = _props.items;
var currentRefinement = _props.currentRefinement;
return _react2.default.createElement(_Select2.default, {
cx: cx,
selectedItem: currentRefinement,
onSelect: refine,
items: items
});
}
}]);
return SortBy;
}(_react.Component);
SortBy.propTypes = {
refine: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string,
value: _react.PropTypes.string.isRequired
})).isRequired,
currentRefinement: _react.PropTypes.string.isRequired,
transformItems: _react.PropTypes.func
};
exports.default = SortBy;
/***/ }),
/* 391 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEmpty2 = __webpack_require__(17);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('StarRating');
var StarRating = function (_Component) {
_inherits(StarRating, _Component);
function StarRating() {
_classCallCheck(this, StarRating);
return _possibleConstructorReturn(this, (StarRating.__proto__ || Object.getPrototypeOf(StarRating)).apply(this, arguments));
}
_createClass(StarRating, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'onClick',
value: function onClick(min, max, e) {
e.preventDefault();
e.stopPropagation();
if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) {
this.props.refine({ min: this.props.min, max: this.props.max });
} else {
this.props.refine({ min: min, max: max });
}
}
}, {
key: 'buildItem',
value: function buildItem(_ref) {
var max = _ref.max;
var lowerBound = _ref.lowerBound;
var count = _ref.count;
var translate = _ref.translate;
var createURL = _ref.createURL;
var isLastSelectableItem = _ref.isLastSelectableItem;
var disabled = !count;
var isCurrentMinLower = this.props.currentRefinement.min < lowerBound;
var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max;
var icons = [];
for (var icon = 0; icon < max; icon++) {
var iconTheme = icon >= lowerBound ? 'ratingIconEmpty' : 'ratingIcon';
icons.push(_react2.default.createElement('span', _extends({
key: icon
}, cx(iconTheme, selected && iconTheme + 'Selected', disabled && iconTheme + 'Disabled'))));
}
// The last item of the list (the default item), should not
// be clickable if it is selected.
var isLastAndSelect = isLastSelectableItem && selected;
var StarsWrapper = isLastAndSelect ? 'div' : 'a';
var onClickHandler = isLastAndSelect ? {} : {
href: createURL({ min: lowerBound, max: max }),
onClick: this.onClick.bind(this, lowerBound, max)
};
return _react2.default.createElement(
StarsWrapper,
_extends({}, cx('ratingLink', selected && 'ratingLinkSelected', disabled && 'ratingLinkDisabled'), {
disabled: disabled,
key: lowerBound
}, onClickHandler),
icons,
_react2.default.createElement(
'span',
cx('ratingLabel', selected && 'ratingLabelSelected', disabled && 'ratingLabelDisabled'),
translate('ratingLabel')
),
_react2.default.createElement(
'span',
null,
' '
),
_react2.default.createElement(
'span',
cx('ratingCount', selected && 'ratingCountSelected', disabled && 'ratingCountDisabled'),
count
)
);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props;
var translate = _props.translate;
var refine = _props.refine;
var min = _props.min;
var max = _props.max;
var count = _props.count;
var createURL = _props.createURL;
var canRefine = _props.canRefine;
var items = [];
var _loop = function _loop(i) {
var hasCount = !(0, _isEmpty3.default)(count.filter(function (item) {
return Number(item.value) === i;
}));
var lastSelectableItem = count.reduce(function (acc, item) {
return item.value < acc.value || !acc.value && hasCount ? item : acc;
}, {});
var itemCount = count.reduce(function (acc, item) {
return item.value >= i && hasCount ? acc + item.count : acc;
}, 0);
items.push(_this2.buildItem({
lowerBound: i,
max: max,
refine: refine,
count: itemCount,
translate: translate,
createURL: createURL,
isLastSelectableItem: i === Number(lastSelectableItem.value)
}));
};
for (var i = max; i >= min; i--) {
_loop(i);
}
return _react2.default.createElement(
'div',
cx('root', !canRefine && 'noRefinement'),
items
);
}
}]);
return StarRating;
}(_react.Component);
StarRating.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
createURL: _react.PropTypes.func.isRequired,
min: _react.PropTypes.number,
max: _react.PropTypes.number,
currentRefinement: _react.PropTypes.shape({
min: _react.PropTypes.number,
max: _react.PropTypes.number
}),
count: _react.PropTypes.arrayOf(_react.PropTypes.shape({
value: _react.PropTypes.string,
count: _react.PropTypes.number
})),
canRefine: _react.PropTypes.bool.isRequired
};
StarRating.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
ratingLabel: ' & Up'
})(StarRating);
/***/ }),
/* 392 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(32);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Stats');
var Stats = function (_Component) {
_inherits(Stats, _Component);
function Stats() {
_classCallCheck(this, Stats);
return _possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments));
}
_createClass(Stats, [{
key: 'render',
value: function render() {
var _props = this.props;
var translate = _props.translate;
var nbHits = _props.nbHits;
var processingTimeMS = _props.processingTimeMS;
return _react2.default.createElement(
'span',
cx('root'),
translate('stats', nbHits, processingTimeMS)
);
}
}]);
return Stats;
}(_react.Component);
Stats.propTypes = {
translate: _react.PropTypes.func.isRequired,
nbHits: _react.PropTypes.number.isRequired,
processingTimeMS: _react.PropTypes.number.isRequired
};
exports.default = (0, _translatable2.default)({
stats: function stats(n, ms) {
return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms';
}
})(Stats);
/***/ }),
/* 393 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _classNames = __webpack_require__(13);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Toggle');
var Toggle = function (_Component) {
_inherits(Toggle, _Component);
function Toggle() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Toggle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Toggle.__proto__ || Object.getPrototypeOf(Toggle)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.refine(e.target.checked);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Toggle, [{
key: 'render',
value: function render() {
var _props = this.props;
var currentRefinement = _props.currentRefinement;
var label = _props.label;
return _react2.default.createElement(
'label',
cx('root'),
_react2.default.createElement('input', _extends({}, cx('checkbox'), {
type: 'checkbox',
checked: currentRefinement,
onChange: this.onChange
})),
_react2.default.createElement(
'span',
cx('label'),
label
)
);
}
}]);
return Toggle;
}(_react.Component);
Toggle.propTypes = {
currentRefinement: _react.PropTypes.bool.isRequired,
refine: _react.PropTypes.func.isRequired,
label: _react.PropTypes.string.isRequired
};
exports.default = Toggle;
/***/ }),
/* 394 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/* eslint valid-jsdoc: 0 */
/**
* @description
* `<Index>` is the component that allows you to apply widgets to a dedicated index. It's
* useful if you want to build an interface that targets multiple indices.
* @kind widget
* @name <Index>
* @propType {string} indexName - index in which to search.
* @example
* import {InstantSearch, Index, SearchBox, Hits, Configure} from 'react-instantsearch/dom';
*
* export default function Search() {
* return (
* <InstantSearch
appId=""
apiKey=""
indexName="index1">
<SearchBox/>
<Configure hitsPerPage={1} />
<Index indexName="index1">
<Hits />
</Index>
<Index indexName="index2">
<Hits />
</Index>
</InstantSearch>
* );
* }
*/
var Index = function (_Component) {
_inherits(Index, _Component);
function Index() {
_classCallCheck(this, Index);
return _possibleConstructorReturn(this, (Index.__proto__ || Object.getPrototypeOf(Index)).apply(this, arguments));
}
_createClass(Index, [{
key: 'getChildContext',
value: function getChildContext() {
return {
multiIndexContext: {
targetedIndex: this.props.indexName
}
};
}
}, {
key: 'render',
value: function render() {
var childrenCount = _react.Children.count(this.props.children);
var _props$root = this.props.root;
var Root = _props$root.Root;
var props = _props$root.props;
if (childrenCount === 0) return null;else return _react2.default.createElement(
Root,
props,
this.props.children
);
}
}]);
return Index;
}(_react.Component);
Index.propTypes = {
// @TODO: These props are currently constant.
indexName: _react.PropTypes.string.isRequired,
children: _react.PropTypes.node,
root: _react.PropTypes.shape({
Root: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.func]),
props: _react.PropTypes.object
}).isRequired
};
Index.childContextTypes = {
// @TODO: more precise widgets manager propType
multiIndexContext: _react.PropTypes.object.isRequired
};
exports.default = Index;
/***/ }),
/* 395 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _createInstantSearchManager = __webpack_require__(396);
var _createInstantSearchManager2 = _interopRequireDefault(_createInstantSearchManager);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function validateNextProps(props, nextProps) {
if (!props.searchState && nextProps.searchState) {
throw new Error('You can\'t switch <InstantSearch> from being uncontrolled to controlled');
} else if (props.searchState && !nextProps.searchState) {
throw new Error('You can\'t switch <InstantSearch> from being controlled to uncontrolled');
}
}
/* eslint valid-jsdoc: 0 */
/**
* @description
* `<InstantSearch>` is the root component of all React InstantSearch implementations.
* It provides all the connected components (aka widgets) a means to interact
* with the searchState.
* @kind widget
* @requirements You will need to have an Algolia account to be able to use this widget.
* [Create one now](https://www.algolia.com/users/sign_up).
* @propType {string} appId - Your Algolia application id.
* @propType {string} apiKey - Your Algolia search-only API key.
* @propType {string} indexName - Main index in which to search.
* @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html).
* @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html).
* @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html).
* @example
* import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom';
*
* export default function Search() {
* return (
* <InstantSearch
* appId="appId"
* apiKey="apiKey"
* indexName="indexName"
* >
* <SearchBox />
* <Hits />
* </InstantSearch>
* );
* }
*/
var InstantSearch = function (_Component) {
_inherits(InstantSearch, _Component);
function InstantSearch(props) {
_classCallCheck(this, InstantSearch);
var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props));
_this.isControlled = Boolean(props.searchState);
var initialState = _this.isControlled ? props.searchState : {};
_this.aisManager = (0, _createInstantSearchManager2.default)({
indexName: props.indexName,
searchParameters: props.searchParameters,
algoliaClient: props.algoliaClient,
initialState: initialState
});
return _this;
}
_createClass(InstantSearch, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
validateNextProps(this.props, nextProps);
if (this.props.indexName !== nextProps.indexName) {
this.aisManager.updateIndex(nextProps.indexName);
}
if (this.isControlled) {
this.aisManager.onExternalStateUpdate(nextProps.searchState);
}
}
}, {
key: 'getChildContext',
value: function getChildContext() {
// If not already cached, cache the bound methods so that we can forward them as part
// of the context.
if (!this._aisContextCache) {
this._aisContextCache = {
ais: {
onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this),
createHrefForState: this.createHrefForState.bind(this),
onSearchForFacetValues: this.onSearchForFacetValues.bind(this),
onSearchStateChange: this.onSearchStateChange.bind(this)
}
};
}
return {
ais: _extends({}, this._aisContextCache.ais, {
store: this.aisManager.store,
widgetsManager: this.aisManager.widgetsManager,
mainTargetedIndex: this.props.indexName
})
};
}
}, {
key: 'createHrefForState',
value: function createHrefForState(searchState) {
searchState = this.aisManager.transitionState(searchState);
return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#';
}
}, {
key: 'onWidgetsInternalStateUpdate',
value: function onWidgetsInternalStateUpdate(searchState) {
searchState = this.aisManager.transitionState(searchState);
this.onSearchStateChange(searchState);
if (!this.isControlled) {
this.aisManager.onExternalStateUpdate(searchState);
}
}
}, {
key: 'onSearchStateChange',
value: function onSearchStateChange(searchState) {
if (this.props.onSearchStateChange) {
this.props.onSearchStateChange(searchState);
}
}
}, {
key: 'onSearchForFacetValues',
value: function onSearchForFacetValues(searchState) {
this.aisManager.onSearchForFacetValues(searchState);
}
}, {
key: 'getKnownKeys',
value: function getKnownKeys() {
return this.aisManager.getWidgetsIds();
}
}, {
key: 'render',
value: function render() {
var childrenCount = _react.Children.count(this.props.children);
var _props$root = this.props.root;
var Root = _props$root.Root;
var props = _props$root.props;
if (childrenCount === 0) return null;else return _react2.default.createElement(
Root,
props,
this.props.children
);
}
}]);
return InstantSearch;
}(_react.Component);
InstantSearch.propTypes = {
// @TODO: These props are currently constant.
indexName: _react.PropTypes.string.isRequired,
algoliaClient: _react.PropTypes.object.isRequired,
searchParameters: _react.PropTypes.object,
createURL: _react.PropTypes.func,
searchState: _react.PropTypes.object,
onSearchStateChange: _react.PropTypes.func,
children: _react.PropTypes.node,
root: _react.PropTypes.shape({
Root: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.func]),
props: _react.PropTypes.object
}).isRequired
};
InstantSearch.childContextTypes = {
// @TODO: more precise widgets manager propType
ais: _react.PropTypes.object.isRequired
};
exports.default = InstantSearch;
/***/ }),
/* 396 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(38);
var _omit3 = _interopRequireDefault(_omit2);
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; };
exports.default = createInstantSearchManager;
var _algoliasearchHelper = __webpack_require__(210);
var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper);
var _createWidgetsManager = __webpack_require__(398);
var _createWidgetsManager2 = _interopRequireDefault(_createWidgetsManager);
var _createStore = __webpack_require__(397);
var _createStore2 = _interopRequireDefault(_createStore);
var _highlightTags = __webpack_require__(209);
var _highlightTags2 = _interopRequireDefault(_highlightTags);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/
function createInstantSearchManager(_ref) {
var indexName = _ref.indexName;
var _ref$initialState = _ref.initialState;
var initialState = _ref$initialState === undefined ? {} : _ref$initialState;
var algoliaClient = _ref.algoliaClient;
var _ref$searchParameters = _ref.searchParameters;
var searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters;
var baseSP = new _algoliasearchHelper.SearchParameters(_extends({}, searchParameters, {
index: indexName
}, _highlightTags2.default));
var helper = (0, _algoliasearchHelper2.default)(algoliaClient, indexName, baseSP);
helper.on('result', handleSearchSuccess);
helper.on('error', handleSearchError);
var derivedHelpers = {};
var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used.
var initialSearchParameters = helper.state;
var widgetsManager = (0, _createWidgetsManager2.default)(onWidgetsUpdate);
var store = (0, _createStore2.default)({
widgets: initialState,
metadata: [],
results: null,
error: null,
searching: false
});
function updateClient(client) {
helper.setClient(client);
search();
}
function getMetadata(state) {
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getMetadata);
}).map(function (widget) {
return widget.getMetadata(state);
});
}
function getSearchParameters() {
indexMapping = {};
var mainParameters = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return !widget.multiIndexContext || widget.multiIndexContext && widget.multiIndexContext.targetedIndex === indexName;
}).reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, initialSearchParameters);
indexMapping[mainParameters.index] = indexName;
var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return widget.multiIndexContext && widget.multiIndexContext.targetedIndex !== indexName;
}).reduce(function (indices, widget) {
var targetedIndex = widget.multiIndexContext.targetedIndex;
var index = indices.find(function (i) {
return i.targetedIndex === targetedIndex;
});
if (index) {
index.widgets.push(widget);
} else {
indices.push({ targetedIndex: targetedIndex, widgets: [widget] });
}
return indices;
}, []);
return { mainParameters: mainParameters, derivatedWidgets: derivatedWidgets };
}
function search() {
var _getSearchParameters = getSearchParameters(helper.state);
var mainParameters = _getSearchParameters.mainParameters;
var derivatedWidgets = _getSearchParameters.derivatedWidgets;
Object.values(derivedHelpers).forEach(function (d) {
return d.detach();
});
derivedHelpers = {};
helper.setState(mainParameters);
derivatedWidgets.forEach(function (derivatedSearchParameters) {
var index = derivatedSearchParameters.targetedIndex;
var derivedHelper = helper.derive(function (sp) {
var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, sp.setIndex(index));
indexMapping[parameters.index] = index;
return parameters;
});
derivedHelper.on('result', handleSearchSuccess);
derivedHelper.on('error', handleSearchError);
derivedHelpers[index] = derivedHelper;
});
helper.search();
}
function handleSearchSuccess(content) {
var state = store.getState();
var results = state.results ? state.results : [];
results[indexMapping[content.index]] = content;
var nextState = (0, _omit3.default)(_extends({}, store.getState(), {
results: results,
searching: false
}), 'resultsFacetValues');
store.setState(nextState);
}
function handleSearchError(error) {
var nextState = (0, _omit3.default)(_extends({}, store.getState(), {
error: error,
searching: false
}), 'resultsFacetValues');
store.setState(nextState);
}
// Called whenever a widget has been rendered with new props.
function onWidgetsUpdate() {
var metadata = getMetadata(store.getState().widgets);
store.setState(_extends({}, store.getState(), {
metadata: metadata,
searching: true
}));
// Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
}
function transitionState(nextSearchState) {
var searchState = store.getState().widgets;
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.transitionState);
}).reduce(function (res, widget) {
return widget.transitionState(searchState, res);
}, nextSearchState);
}
function onExternalStateUpdate(nextSearchState) {
var metadata = getMetadata(nextSearchState);
store.setState(_extends({}, store.getState(), {
widgets: nextSearchState,
metadata: metadata,
searching: true
}));
search();
}
function onSearchForFacetValues(nextSearchState) {
store.setState(_extends({}, store.getState(), {
searchingForFacetValues: true
}));
helper.searchForFacetValues(nextSearchState.facetName, nextSearchState.query).then(function (content) {
var _extends2;
store.setState(_extends({}, store.getState(), {
resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_extends2 = {}, _defineProperty(_extends2, nextSearchState.facetName, content.facetHits), _defineProperty(_extends2, 'query', nextSearchState.query), _extends2)),
searchingForFacetValues: false
}));
}, function (error) {
store.setState(_extends({}, store.getState(), {
error: error,
searchingForFacetValues: false
}));
}).catch(function (error) {
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(function () {
throw error;
});
});
}
function updateIndex(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
search();
}
function getWidgetsIds() {
return store.getState().metadata.reduce(function (res, meta) {
return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res;
}, []);
}
return {
store: store,
widgetsManager: widgetsManager,
getWidgetsIds: getWidgetsIds,
onExternalStateUpdate: onExternalStateUpdate,
transitionState: transitionState,
onSearchForFacetValues: onSearchForFacetValues,
updateClient: updateClient,
updateIndex: updateIndex
};
}
/***/ }),
/* 397 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createStore;
function createStore(initialState) {
var state = initialState;
var listeners = [];
function dispatch() {
listeners.forEach(function (listener) {
return listener();
});
}
return {
getState: function getState() {
return state;
},
setState: function setState(nextState) {
state = nextState;
dispatch();
},
subscribe: function subscribe(listener) {
listeners.push(listener);
return function unsubcribe() {
listeners.splice(listeners.indexOf(listener), 1);
};
}
};
}
/***/ }),
/* 398 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createWidgetsManager;
var _utils = __webpack_require__(56);
function createWidgetsManager(onWidgetsUpdate) {
var widgets = [];
// Is an update scheduled?
var scheduled = false;
// The state manager's updates need to be batched since more than one
// component can register or unregister widgets during the same tick.
function scheduleUpdate() {
if (scheduled) {
return;
}
scheduled = true;
(0, _utils.defer)(function () {
scheduled = false;
onWidgetsUpdate();
});
}
return {
registerWidget: function registerWidget(widget) {
widgets.push(widget);
scheduleUpdate();
return function unregisterWidget() {
widgets.splice(widgets.indexOf(widget), 1);
scheduleUpdate();
};
},
update: scheduleUpdate,
getWidgets: function getWidgets() {
return widgets;
}
};
}
/***/ }),
/* 399 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.withKeysPropType = exports.stateManagerPropType = exports.configManagerPropType = undefined;
var _react = __webpack_require__(0);
var configManagerPropType = exports.configManagerPropType = _react.PropTypes.shape({
register: _react.PropTypes.func.isRequired,
swap: _react.PropTypes.func.isRequired,
unregister: _react.PropTypes.func.isRequired
});
var stateManagerPropType = exports.stateManagerPropType = _react.PropTypes.shape({
createURL: _react.PropTypes.func.isRequired,
setState: _react.PropTypes.func.isRequired,
getState: _react.PropTypes.func.isRequired,
unlisten: _react.PropTypes.func.isRequired
});
var withKeysPropType = exports.withKeysPropType = function withKeysPropType(keys) {
return function (props, propName, componentName) {
var prop = props[propName];
if (prop) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
if (keys.indexOf(key) === -1) {
return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.'));
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return undefined;
};
};
/***/ }),
/* 400 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {module.exports = AlgoliaSearchCore;
var errors = __webpack_require__(211);
var exitPromise = __webpack_require__(408);
var IndexCore = __webpack_require__(401);
var store = __webpack_require__(412);
// We will always put the API KEY in the JSON body in case of too long API KEY,
// to avoid query string being too long and failing in various conditions (our server limit, browser limit,
// proxies limit)
var MAX_API_KEY_LENGTH = 500;
var RESET_APP_DATA_TIMER =
process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) ||
60 * 2 * 1000; // after 2 minutes reset to first host
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = __webpack_require__(212)('algoliasearch');
var clone = __webpack_require__(118);
var isArray = __webpack_require__(245);
var map = __webpack_require__(244);
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
this.hosts = {
read: [],
write: []
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
this._timeouts = opts.timeouts || {
connect: 1 * 1000, // 500ms connect is GPRS latency
read: 2 * 1000,
write: 30 * 1000
};
// backward compat, if opts.timeout is passed, we use it to configure all timeouts like before
if (opts.timeout) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout;
}
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
this._checkAppIdData();
if (!opts.hosts) {
var defaultHosts = map(this._shuffleResult, function(hostNumber) {
return applicationID + '-' + hostNumber + '.algolianet.com';
});
// no hosts given, compute defaults
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
// when passing custom hosts, we need to have a different host index if the number
// of write/read hosts are different.
this.hosts.read = clone(opts.hosts);
this.hosts.write = clone(opts.hosts);
} else {
this.hosts.read = clone(opts.hosts.read);
this.hosts.write = clone(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.extraHeaders = [];
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders.push({
name: name.toLowerCase(), value: value
});
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
if (this._ua.indexOf(';' + algoliaAgent) === -1) {
this._ua += ';' + algoliaAgent;
}
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
this._checkAppIdData();
var requestDebug = __webpack_require__(212)('algoliasearch:' + initialOpts.url);
var body;
var additionalUA = initialOpts.additionalUA || '';
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(additionalUA, false);
} else {
headers = this._computeRequestHeaders(additionalUA);
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
client._checkAppIdData();
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to [email protected] to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders(additionalUA);
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
client._setHostIndexByType(0, initialOpts.hostType);
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client._getHostByType(initialOpts.hostType);
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeouts: reqOpts.timeouts,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeouts: %d',
options.method, url, options.headers, options.timeouts);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client._incrementHostIndex(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client._incrementHostIndex(initialOpts.hostType);
client._incrementTimeoutMultipler();
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeouts: client._getTimeoutsForRequest(initialOpts.hostType)
}
);
// either we have a callback
// either we are using promises
if (initialOpts.callback) {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
* @param {object} args arguments to add to the current query string
* @param {string} params current query string
* @return {string} the final query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) {
var forEach = __webpack_require__(109);
var ua = additionalUA ?
this._ua + ';' + additionalUA :
this._ua;
var requestHeaders = {
'x-algolia-agent': ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
if (this.extraHeaders) {
forEach(this.extraHeaders, function addToRequestHeaders(header) {
requestHeaders[header.name] = header.value;
});
}
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = __webpack_require__(245);
var map = __webpack_require__(244);
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
* @deprecated
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds;
}
};
/**
* Set the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) {
this._timeouts = timeouts;
};
/**
* Get the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.getTimeouts = function() {
return this._timeouts;
};
AlgoliaSearchCore.prototype._getAppIdData = function() {
var data = store.get(this.applicationID);
if (data !== null) this._cacheAppIdData(data);
return data;
};
AlgoliaSearchCore.prototype._setAppIdData = function(data) {
data.lastChange = (new Date()).getTime();
this._cacheAppIdData(data);
return store.set(this.applicationID, data);
};
AlgoliaSearchCore.prototype._checkAppIdData = function() {
var data = this._getAppIdData();
var now = (new Date()).getTime();
if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) {
return this._resetInitialAppIdData(data);
}
return data;
};
AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) {
var newData = data || {};
newData.hostIndexes = {read: 0, write: 0};
newData.timeoutMultiplier = 1;
newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]);
return this._setAppIdData(newData);
};
AlgoliaSearchCore.prototype._cacheAppIdData = function(data) {
this._hostIndexes = data.hostIndexes;
this._timeoutMultiplier = data.timeoutMultiplier;
this._shuffleResult = data.shuffleResult;
};
AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) {
var foreach = __webpack_require__(109);
var currentData = this._getAppIdData();
foreach(newData, function(value, key) {
currentData[key] = value;
});
return this._setAppIdData(currentData);
};
AlgoliaSearchCore.prototype._getHostByType = function(hostType) {
return this.hosts[hostType][this._getHostIndexByType(hostType)];
};
AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() {
return this._timeoutMultiplier;
};
AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) {
return this._hostIndexes[hostType];
};
AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) {
var clone = __webpack_require__(118);
var newHostIndexes = clone(this._hostIndexes);
newHostIndexes[hostType] = hostIndex;
this._partialAppIdDataUpdate({hostIndexes: newHostIndexes});
return hostIndex;
};
AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) {
return this._setHostIndexByType(
(this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType
);
};
AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() {
var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4);
return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier});
};
AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) {
return {
connect: this._timeouts.connect * this._timeoutMultiplier,
complete: this._timeouts[hostType] * this._timeoutMultiplier
};
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(108)))
/***/ }),
/* 401 */
/***/ (function(module, exports, __webpack_require__) {
var buildSearchMethod = __webpack_require__(344);
var deprecate = __webpack_require__(406);
var deprecatedMessage = __webpack_require__(407);
module.exports = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the full text query
* @param {object} [args] (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param {function} [callback] the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the similar query
* @param {object} [args] (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = __webpack_require__(409);
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse',
body: {params: params},
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse',
body: {cursor: cursor},
hostType: 'read',
callback: callback
});
};
/*
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchForFacetValues = function(params, callback) {
var clone = __webpack_require__(118);
var omit = __webpack_require__(410);
var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
return this.searchForFacetValues(params, callback);
}, deprecatedMessage(
'index.searchFacet(params[, callback])',
'index.searchForFacetValues(params[, callback])'
));
IndexCore.prototype._search = function(params, url, callback, additionalUA) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback,
additionalUA: additionalUA
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = __webpack_require__(245);
var map = __webpack_require__(244);
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
/***/ }),
/* 402 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(417);
var Promise = global.Promise || __webpack_require__(416).Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = __webpack_require__(345);
var errors = __webpack_require__(211);
var inlineHeaders = __webpack_require__(404);
var jsonpRequest = __webpack_require__(405);
var places = __webpack_require__(411);
uaSuffix = uaSuffix || '';
if (false) {
require('debug').enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = __webpack_require__(118);
var getDocumentProtocol = __webpack_require__(403);
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = __webpack_require__(413);
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
global.__algolia = {
debug: __webpack_require__(212),
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in global,
hasXDomainRequest: 'XDomainRequest' in global
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var reqTimeout;
var timedOut;
var connected = false;
reqTimeout = setTimeout(onTimeout, opts.timeouts.connect);
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = onProgress;
if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange;
req.onload = onLoad;
req.onerror = onError;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
// headers are meant to be sent after open
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function onLoad(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function onError(event) {
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors.Network({
more: event
})
);
}
function onTimeout() {
timedOut = true;
req.abort();
reject(new errors.RequestTimeout());
}
function onConnect() {
connected = true;
clearTimeout(reqTimeout);
reqTimeout = setTimeout(onTimeout, opts.timeouts.complete);
}
function onProgress() {
if (!connected) onConnect();
}
function onReadyStateChange() {
if (!connected && req.readyState > 1) onConnect();
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise.reject(val);
},
resolve: function resolvePromise(val) {
return Promise.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
/***/ }),
/* 403 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
/***/ }),
/* 404 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = inlineHeaders;
var encode = __webpack_require__(424);
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode(headers);
}
/***/ }),
/* 405 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = jsonpRequest;
var errors = __webpack_require__(211);
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeouts.complete);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
/***/ }),
/* 406 */
/***/ (function(module, exports) {
module.exports = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.log(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
/***/ }),
/* 407 */
/***/ (function(module, exports) {
module.exports = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace('.', '')
.replace('()', '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink;
};
/***/ }),
/* 408 */
/***/ (function(module, exports) {
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
module.exports = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
/***/ }),
/* 409 */
/***/ (function(module, exports, __webpack_require__) {
var foreach = __webpack_require__(109);
module.exports = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
/***/ }),
/* 410 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = function omit(obj, test) {
var keys = __webpack_require__(422);
var foreach = __webpack_require__(109);
var filtered = {};
foreach(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
/***/ }),
/* 411 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = createPlacesClient;
var buildSearchMethod = __webpack_require__(344);
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = __webpack_require__(118);
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod('query', '/1/places/query');
return index;
};
}
/***/ }),
/* 412 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var debug = __webpack_require__(212)('algoliasearch:src/hostIndexState.js');
var localStorageNamespace = 'algoliasearch-client-js';
var store;
var moduleStore = {
state: {},
set: function(key, data) {
this.state[key] = data;
return this.state[key];
},
get: function(key) {
return this.state[key] || null;
}
};
var localStorageStore = {
set: function(key, data) {
moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure
try {
var namespace = JSON.parse(global.localStorage[localStorageNamespace]);
namespace[key] = data;
global.localStorage[localStorageNamespace] = JSON.stringify(namespace);
return namespace[key];
} catch (e) {
return localStorageFailure(key, e);
}
},
get: function(key) {
try {
return JSON.parse(global.localStorage[localStorageNamespace])[key] || null;
} catch (e) {
return localStorageFailure(key, e);
}
}
};
function localStorageFailure(key, e) {
debug('localStorage failed with', e);
cleanup();
store = moduleStore;
return store.get(key);
}
store = supportsLocalStorage() ? localStorageStore : moduleStore;
module.exports = {
get: getOrSet,
set: getOrSet,
supportsLocalStorage: supportsLocalStorage
};
function getOrSet(key, data) {
if (arguments.length === 1) {
return store.get(key);
}
return store.set(key, data);
}
function supportsLocalStorage() {
try {
if ('localStorage' in global &&
global.localStorage !== null) {
if (!global.localStorage[localStorageNamespace]) {
// actual creation of the namespace
global.localStorage.setItem(localStorageNamespace, JSON.stringify({}));
}
return true;
}
return false;
} catch (_) {
return false;
}
}
// In case of any error on localStorage, we clean our own namespace, this should handle
// quota errors when a lot of keys + data are used
function cleanup() {
try {
global.localStorage.removeItem(localStorageNamespace);
} catch (_) {
// nothing to do
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53)))
/***/ }),
/* 413 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = '3.21.1';
/***/ }),
/* 414 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ }),
/* 415 */
/***/ (function(module, exports, __webpack_require__) {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug.debug = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = __webpack_require__(421);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting
args = exports.formatArgs.apply(self, args);
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
/***/ }),
/* 416 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process, global) {var require;/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 4.0.5
*/
(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
return typeof x === 'function' || typeof x === 'object' && x !== null;
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (!Array.isArray) {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
_isArray = Array.isArray;
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = require;
var vertx = __webpack_require__(426);
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && "function" === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
_resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
_reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
_reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
_reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return _resolve(promise, value);
}, function (reason) {
return _reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$) {
if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$ === GET_THEN_ERROR) {
_reject(promise, GET_THEN_ERROR.error);
} else if (then$$ === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$)) {
handleForeignThenable(promise, maybeThenable, then$$);
} else {
fulfill(promise, maybeThenable);
}
}
}
function _resolve(promise, value) {
if (promise === value) {
_reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function _reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
_reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
_resolve(promise, value);
} else if (failed) {
_reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
_reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
_resolve(promise, value);
}, function rejectPromise(reason) {
_reject(promise, reason);
});
} catch (e) {
_reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
_reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._enumerate = function () {
var length = this.length;
var _input = this._input;
for (var i = 0; this._state === PENDING && i < length; i++) {
this._eachEntry(_input[i], i);
}
};
Enumerator.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$ = c.resolve;
if (resolve$$ === resolve) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$) {
return resolve$$(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$(entry), i);
}
};
Enumerator.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
_reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
Promise.prototype = {
constructor: Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
function polyfill() {
var local = undefined;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise;
}
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
return Promise;
})));
//# sourceMappingURL=es6-promise.map
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(108), __webpack_require__(53)))
/***/ }),
/* 417 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53)))
/***/ }),
/* 418 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeMax = Math.max;
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
module.exports = baseRange;
/***/ }),
/* 419 */
/***/ (function(module, exports, __webpack_require__) {
var baseRange = __webpack_require__(418),
isIterateeCall = __webpack_require__(213),
toFinite = __webpack_require__(215);
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
module.exports = createRange;
/***/ }),
/* 420 */
/***/ (function(module, exports, __webpack_require__) {
var createRange = __webpack_require__(419);
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = createRange();
module.exports = range;
/***/ }),
/* 421 */
/***/ (function(module, exports) {
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}
/***/ }),
/* 422 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = __webpack_require__(423);
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
/***/ }),
/* 423 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
/***/ }),
/* 424 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
/***/ }),
/* 425 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_425__;
/***/ }),
/* 426 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 427 */,
/* 428 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Panel = exports.Toggle = exports.Stats = exports.SortBy = exports.SearchBox = exports.ScrollTo = exports.ClearAll = exports.RefinementList = exports.StarRating = exports.RangeSlider = exports.RangeInput = exports.PoweredBy = exports.Pagination = exports.MultiRange = exports.Menu = exports.InfiniteHits = exports.HitsPerPage = exports.Hits = exports.Snippet = exports.Highlight = exports.HierarchicalMenu = exports.CurrentRefinements = exports.Configure = exports.Index = exports.InstantSearch = undefined;
var _Configure = __webpack_require__(350);
Object.defineProperty(exports, 'Configure', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Configure).default;
}
});
var _CurrentRefinements = __webpack_require__(351);
Object.defineProperty(exports, 'CurrentRefinements', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_CurrentRefinements).default;
}
});
var _HierarchicalMenu = __webpack_require__(352);
Object.defineProperty(exports, 'HierarchicalMenu', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_HierarchicalMenu).default;
}
});
var _Highlight = __webpack_require__(231);
Object.defineProperty(exports, 'Highlight', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Highlight).default;
}
});
var _Snippet = __webpack_require__(366);
Object.defineProperty(exports, 'Snippet', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Snippet).default;
}
});
var _Hits = __webpack_require__(353);
Object.defineProperty(exports, 'Hits', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Hits).default;
}
});
var _HitsPerPage = __webpack_require__(354);
Object.defineProperty(exports, 'HitsPerPage', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_HitsPerPage).default;
}
});
var _InfiniteHits = __webpack_require__(355);
Object.defineProperty(exports, 'InfiniteHits', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_InfiniteHits).default;
}
});
var _Menu = __webpack_require__(356);
Object.defineProperty(exports, 'Menu', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Menu).default;
}
});
var _MultiRange = __webpack_require__(357);
Object.defineProperty(exports, 'MultiRange', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_MultiRange).default;
}
});
var _Pagination = __webpack_require__(358);
Object.defineProperty(exports, 'Pagination', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Pagination).default;
}
});
var _PoweredBy = __webpack_require__(360);
Object.defineProperty(exports, 'PoweredBy', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_PoweredBy).default;
}
});
var _RangeInput = __webpack_require__(361);
Object.defineProperty(exports, 'RangeInput', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_RangeInput).default;
}
});
var _RangeSlider = __webpack_require__(362);
Object.defineProperty(exports, 'RangeSlider', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_RangeSlider).default;
}
});
var _StarRating = __webpack_require__(368);
Object.defineProperty(exports, 'StarRating', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_StarRating).default;
}
});
var _RefinementList = __webpack_require__(363);
Object.defineProperty(exports, 'RefinementList', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_RefinementList).default;
}
});
var _ClearAll = __webpack_require__(349);
Object.defineProperty(exports, 'ClearAll', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_ClearAll).default;
}
});
var _ScrollTo = __webpack_require__(364);
Object.defineProperty(exports, 'ScrollTo', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_ScrollTo).default;
}
});
var _SearchBox = __webpack_require__(365);
Object.defineProperty(exports, 'SearchBox', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_SearchBox).default;
}
});
var _SortBy = __webpack_require__(367);
Object.defineProperty(exports, 'SortBy', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_SortBy).default;
}
});
var _Stats = __webpack_require__(369);
Object.defineProperty(exports, 'Stats', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Stats).default;
}
});
var _Toggle = __webpack_require__(370);
Object.defineProperty(exports, 'Toggle', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Toggle).default;
}
});
var _Panel = __webpack_require__(359);
Object.defineProperty(exports, 'Panel', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Panel).default;
}
});
var _createInstantSearch = __webpack_require__(348);
var _createInstantSearch2 = _interopRequireDefault(_createInstantSearch);
var _createIndex = __webpack_require__(347);
var _createIndex2 = _interopRequireDefault(_createIndex);
var _lite = __webpack_require__(371);
var _lite2 = _interopRequireDefault(_lite);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var InstantSearch = (0, _createInstantSearch2.default)(_lite2.default, {
Root: 'div',
props: { className: 'ais-InstantSearch__root' }
});
exports.InstantSearch = InstantSearch;
var Index = (0, _createIndex2.default)({
Root: 'div',
props: { className: 'ais-MultiIndex__root' }
});
exports.Index = Index;
/***/ })
/******/ ]);
});
//# sourceMappingURL=Dom.js.map |
src/routes.js | rongkaixia/web-server | import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
App,
Chat,
Home,
Login,
LoginSuccess,
Logout,
Signup,
Widgets,
UserCenter,
UserCenterHome,
AccountInfo,
AccountAddress,
AccountCoupon,
AccountOrder,
OrderDetail,
Necklace,
BuyNecklace,
Cart,
Checkout,
Payment,
Survey,
NotFound,
} from 'containers';
export default (store) => {
const requireLogin = (nextState, replace, cb) => {
function checkAuth() {
const { userInfo: { user }} = store.getState();
if (!user) {
// oops, not logged in, so can't be here!
replace('/');
}
cb();
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth);
} else {
checkAuth();
}
};
const requireNotLogin = (nextState, replace, cb) => {
function checkAuth() {
const { userInfo: { user }} = store.getState();
if (user) {
// oops, logged in, so can't be here!
replace('/');
}
cb();
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth);
} else {
checkAuth();
}
};
/**
* Please keep routes in alphabetical order
*/
// TODO: 把UserCenter改成跟App类似的结构
return (
<Route path="/" component={App}>
{ /* Home (main) route */ }
<IndexRoute component={Home}/>
{ /* Routes requiring login */ }
<Route onEnter={requireLogin}>
<Route path="chat" component={Chat}/>
<Route path="loginSuccess" component={LoginSuccess}/>
<Route path="logout" component={Logout}/>
<Route path="account" component={UserCenter}>
<IndexRoute component={UserCenterHome}/>
<Route path="order" component={AccountOrder}/>
<Route path="order/detail/:id" component={OrderDetail}/>
<Route path="info" component={AccountInfo}/>
<Route path="address" component={AccountAddress}/>
<Route path="coupon" component={AccountCoupon}/>
</Route>
</Route>
<Route path="necklace" component={Necklace}/>
<Route path="shop/buy-necklace/:id" component={BuyNecklace}/>
<Route path="cart" component={Cart}/>
<Route path="buy/checkout/:id" component={Checkout}/>
<Route path="buy/payment" component={Payment}/>
{ /* Routes */ }
<Route onEnter={requireNotLogin}>
<Route path="login" component={Login}/>
<Route path="signup" component={Signup}/>
</Route>
<Route path="signup" component={Signup}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>
{ /* Catch all route */ }
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
ajax/libs/angular.js/0.9.7/angular-scenario.min.js | JeyKeu/cdnjs | /*!
* 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(aM,C){var a=function(aY,aZ){return new a.fn.init(aY,aZ)},n=aM.jQuery,R=aM.$,ab=aM.document,X,P=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,aW=/^.[^:#\[\.,]*$/,ax=/\S/,M=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,e=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,b=navigator.userAgent,u,K=false,ad=[],aG,at=Object.prototype.toString,ap=Object.prototype.hasOwnProperty,g=Array.prototype.push,F=Array.prototype.slice,s=Array.prototype.indexOf;a.fn=a.prototype={init:function(aY,a1){var a0,a2,aZ,a3;if(!aY){return this}if(aY.nodeType){this.context=this[0]=aY;this.length=1;return this}if(aY==="body"&&!a1){this.context=ab;this[0]=ab.body;this.selector="body";this.length=1;return this}if(typeof aY==="string"){a0=P.exec(aY);if(a0&&(a0[1]||!a1)){if(a0[1]){a3=(a1?a1.ownerDocument||a1:ab);aZ=e.exec(aY);if(aZ){if(a.isPlainObject(a1)){aY=[ab.createElement(aZ[1])];a.fn.attr.call(aY,a1,true)}else{aY=[a3.createElement(aZ[1])]}}else{aZ=J([a0[1]],[a3]);aY=(aZ.cacheable?aZ.fragment.cloneNode(true):aZ.fragment).childNodes}return a.merge(this,aY)}else{a2=ab.getElementById(a0[2]);if(a2){if(a2.id!==a0[2]){return X.find(aY)}this.length=1;this[0]=a2}this.context=ab;this.selector=aY;return this}}else{if(!a1&&/^\w+$/.test(aY)){this.selector=aY;this.context=ab;aY=ab.getElementsByTagName(aY);return a.merge(this,aY)}else{if(!a1||a1.jquery){return(a1||X).find(aY)}else{return a(a1).find(aY)}}}}else{if(a.isFunction(aY)){return X.ready(aY)}}if(aY.selector!==C){this.selector=aY.selector;this.context=aY.context}return a.makeArray(aY,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(aY){return aY==null?this.toArray():(aY<0?this.slice(aY)[0]:this[aY])},pushStack:function(aZ,a1,aY){var a0=a();if(a.isArray(aZ)){g.apply(a0,aZ)}else{a.merge(a0,aZ)}a0.prevObject=this;a0.context=this.context;if(a1==="find"){a0.selector=this.selector+(this.selector?" ":"")+aY}else{if(a1){a0.selector=this.selector+"."+a1+"("+aY+")"}}return a0},each:function(aZ,aY){return a.each(this,aZ,aY)},ready:function(aY){a.bindReady();if(a.isReady){aY.call(ab,a)}else{if(ad){ad.push(aY)}}return this},eq:function(aY){return aY===-1?this.slice(aY):this.slice(aY,+aY+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(aY){return this.pushStack(a.map(this,function(a0,aZ){return aY.call(a0,aZ,a0)}))},end:function(){return this.prevObject||a(null)},push:g,sort:[].sort,splice:[].splice};a.fn.init.prototype=a.fn;a.extend=a.fn.extend=function(){var a3=arguments[0]||{},a2=1,a1=arguments.length,a5=false,a6,a0,aY,aZ;if(typeof a3==="boolean"){a5=a3;a3=arguments[1]||{};a2=2}if(typeof a3!=="object"&&!a.isFunction(a3)){a3={}}if(a1===a2){a3=this;--a2}for(;a2<a1;a2++){if((a6=arguments[a2])!=null){for(a0 in a6){aY=a3[a0];aZ=a6[a0];if(a3===aZ){continue}if(a5&&aZ&&(a.isPlainObject(aZ)||a.isArray(aZ))){var a4=aY&&(a.isPlainObject(aY)||a.isArray(aY))?aY:a.isArray(aZ)?[]:{};a3[a0]=a.extend(a5,a4,aZ)}else{if(aZ!==C){a3[a0]=aZ}}}}}return a3};a.extend({noConflict:function(aY){aM.$=R;if(aY){aM.jQuery=n}return a},isReady:false,ready:function(){if(!a.isReady){if(!ab.body){return setTimeout(a.ready,13)}a.isReady=true;if(ad){var aZ,aY=0;while((aZ=ad[aY++])){aZ.call(ab,a)}ad=null}if(a.fn.triggerHandler){a(ab).triggerHandler("ready")}}},bindReady:function(){if(K){return}K=true;if(ab.readyState==="complete"){return a.ready()}if(ab.addEventListener){ab.addEventListener("DOMContentLoaded",aG,false);aM.addEventListener("load",a.ready,false)}else{if(ab.attachEvent){ab.attachEvent("onreadystatechange",aG);aM.attachEvent("onload",a.ready);var aY=false;try{aY=aM.frameElement==null}catch(aZ){}if(ab.documentElement.doScroll&&aY){x()}}}},isFunction:function(aY){return at.call(aY)==="[object Function]"},isArray:function(aY){return at.call(aY)==="[object Array]"},isPlainObject:function(aZ){if(!aZ||at.call(aZ)!=="[object Object]"||aZ.nodeType||aZ.setInterval){return false}if(aZ.constructor&&!ap.call(aZ,"constructor")&&!ap.call(aZ.constructor.prototype,"isPrototypeOf")){return false}var aY;for(aY in aZ){}return aY===C||ap.call(aZ,aY)},isEmptyObject:function(aZ){for(var aY in aZ){return false}return true},error:function(aY){throw aY},parseJSON:function(aY){if(typeof aY!=="string"||!aY){return null}aY=a.trim(aY);if(/^[\],:{}\s]*$/.test(aY.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){return aM.JSON&&aM.JSON.parse?aM.JSON.parse(aY):(new Function("return "+aY))()}else{a.error("Invalid JSON: "+aY)}},noop:function(){},globalEval:function(a0){if(a0&&ax.test(a0)){var aZ=ab.getElementsByTagName("head")[0]||ab.documentElement,aY=ab.createElement("script");aY.type="text/javascript";if(a.support.scriptEval){aY.appendChild(ab.createTextNode(a0))}else{aY.text=a0}aZ.insertBefore(aY,aZ.firstChild);aZ.removeChild(aY)}},nodeName:function(aZ,aY){return aZ.nodeName&&aZ.nodeName.toUpperCase()===aY.toUpperCase()},each:function(a1,a5,a0){var aZ,a2=0,a3=a1.length,aY=a3===C||a.isFunction(a1);if(a0){if(aY){for(aZ in a1){if(a5.apply(a1[aZ],a0)===false){break}}}else{for(;a2<a3;){if(a5.apply(a1[a2++],a0)===false){break}}}}else{if(aY){for(aZ in a1){if(a5.call(a1[aZ],aZ,a1[aZ])===false){break}}}else{for(var a4=a1[0];a2<a3&&a5.call(a4,a2,a4)!==false;a4=a1[++a2]){}}}return a1},trim:function(aY){return(aY||"").replace(M,"")},makeArray:function(a0,aZ){var aY=aZ||[];if(a0!=null){if(a0.length==null||typeof a0==="string"||a.isFunction(a0)||(typeof a0!=="function"&&a0.setInterval)){g.call(aY,a0)}else{a.merge(aY,a0)}}return aY},inArray:function(a0,a1){if(a1.indexOf){return a1.indexOf(a0)}for(var aY=0,aZ=a1.length;aY<aZ;aY++){if(a1[aY]===a0){return aY}}return -1},merge:function(a2,a0){var a1=a2.length,aZ=0;if(typeof a0.length==="number"){for(var aY=a0.length;aZ<aY;aZ++){a2[a1++]=a0[aZ]}}else{while(a0[aZ]!==C){a2[a1++]=a0[aZ++]}}a2.length=a1;return a2},grep:function(aZ,a3,aY){var a0=[];for(var a1=0,a2=aZ.length;a1<a2;a1++){if(!aY!==!a3(aZ[a1],a1)){a0.push(aZ[a1])}}return a0},map:function(aZ,a4,aY){var a0=[],a3;for(var a1=0,a2=aZ.length;a1<a2;a1++){a3=a4(aZ[a1],a1,aY);if(a3!=null){a0[a0.length]=a3}}return a0.concat.apply([],a0)},guid:1,proxy:function(a0,aZ,aY){if(arguments.length===2){if(typeof aZ==="string"){aY=a0;a0=aY[aZ];aZ=C}else{if(aZ&&!a.isFunction(aZ)){aY=aZ;aZ=C}}}if(!aZ&&a0){aZ=function(){return a0.apply(aY||this,arguments)}}if(a0){aZ.guid=a0.guid=a0.guid||aZ.guid||a.guid++}return aZ},uaMatch:function(aZ){aZ=aZ.toLowerCase();var aY=/(webkit)[ \/]([\w.]+)/.exec(aZ)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(aZ)||/(msie) ([\w.]+)/.exec(aZ)||!/compatible/.test(aZ)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(aZ)||[];return{browser:aY[1]||"",version:aY[2]||"0"}},browser:{}});u=a.uaMatch(b);if(u.browser){a.browser[u.browser]=true;a.browser.version=u.version}if(a.browser.webkit){a.browser.safari=true}if(s){a.inArray=function(aY,aZ){return s.call(aZ,aY)}}X=a(ab);if(ab.addEventListener){aG=function(){ab.removeEventListener("DOMContentLoaded",aG,false);a.ready()}}else{if(ab.attachEvent){aG=function(){if(ab.readyState==="complete"){ab.detachEvent("onreadystatechange",aG);a.ready()}}}}function x(){if(a.isReady){return}try{ab.documentElement.doScroll("left")}catch(aY){setTimeout(x,1);return}a.ready()}function aV(aY,aZ){if(aZ.src){a.ajax({url:aZ.src,async:false,dataType:"script"})}else{a.globalEval(aZ.text||aZ.textContent||aZ.innerHTML||"")}if(aZ.parentNode){aZ.parentNode.removeChild(aZ)}}function an(aY,a6,a4,a0,a3,a5){var aZ=aY.length;if(typeof a6==="object"){for(var a1 in a6){an(aY,a1,a6[a1],a0,a3,a4)}return aY}if(a4!==C){a0=!a5&&a0&&a.isFunction(a4);for(var a2=0;a2<aZ;a2++){a3(aY[a2],a6,a0?a4.call(aY[a2],a2,a3(aY[a2],a6)):a4,a5)}return aY}return aZ?a3(aY[0],a6):C}function aP(){return(new Date).getTime()}(function(){a.support={};var a4=ab.documentElement,a3=ab.createElement("script"),aY=ab.createElement("div"),aZ="script"+aP();aY.style.display="none";aY.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var a6=aY.getElementsByTagName("*"),a5=aY.getElementsByTagName("a")[0];if(!a6||!a6.length||!a5){return}a.support={leadingWhitespace:aY.firstChild.nodeType===3,tbody:!aY.getElementsByTagName("tbody").length,htmlSerialize:!!aY.getElementsByTagName("link").length,style:/red/.test(a5.getAttribute("style")),hrefNormalized:a5.getAttribute("href")==="/a",opacity:/^0.55$/.test(a5.style.opacity),cssFloat:!!a5.style.cssFloat,checkOn:aY.getElementsByTagName("input")[0].value==="on",optSelected:ab.createElement("select").appendChild(ab.createElement("option")).selected,parentNode:aY.removeChild(aY.appendChild(ab.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};a3.type="text/javascript";try{a3.appendChild(ab.createTextNode("window."+aZ+"=1;"))}catch(a1){}a4.insertBefore(a3,a4.firstChild);if(aM[aZ]){a.support.scriptEval=true;delete aM[aZ]}try{delete a3.test}catch(a1){a.support.deleteExpando=false}a4.removeChild(a3);if(aY.attachEvent&&aY.fireEvent){aY.attachEvent("onclick",function a7(){a.support.noCloneEvent=false;aY.detachEvent("onclick",a7)});aY.cloneNode(true).fireEvent("onclick")}aY=ab.createElement("div");aY.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var a0=ab.createDocumentFragment();a0.appendChild(aY.firstChild);a.support.checkClone=a0.cloneNode(true).cloneNode(true).lastChild.checked;a(function(){var a8=ab.createElement("div");a8.style.width=a8.style.paddingLeft="1px";ab.body.appendChild(a8);a.boxModel=a.support.boxModel=a8.offsetWidth===2;ab.body.removeChild(a8).style.display="none";a8=null});var a2=function(a8){var ba=ab.createElement("div");a8="on"+a8;var a9=(a8 in ba);if(!a9){ba.setAttribute(a8,"return;");a9=typeof ba[a8]==="function"}ba=null;return a9};a.support.submitBubbles=a2("submit");a.support.changeBubbles=a2("change");a4=a3=aY=a6=a5=null})();a.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var aI="jQuery"+aP(),aH=0,aT={};a.extend({cache:{},expando:aI,noData:{embed:true,object:true,applet:true},data:function(a0,aZ,a2){if(a0.nodeName&&a.noData[a0.nodeName.toLowerCase()]){return}a0=a0==aM?aT:a0;var a3=a0[aI],aY=a.cache,a1;if(!a3&&typeof aZ==="string"&&a2===C){return null}if(!a3){a3=++aH}if(typeof aZ==="object"){a0[aI]=a3;a1=aY[a3]=a.extend(true,{},aZ)}else{if(!aY[a3]){a0[aI]=a3;aY[a3]={}}}a1=aY[a3];if(a2!==C){a1[aZ]=a2}return typeof aZ==="string"?a1[aZ]:a1},removeData:function(a0,aZ){if(a0.nodeName&&a.noData[a0.nodeName.toLowerCase()]){return}a0=a0==aM?aT:a0;var a2=a0[aI],aY=a.cache,a1=aY[a2];if(aZ){if(a1){delete a1[aZ];if(a.isEmptyObject(a1)){a.removeData(a0)}}}else{if(a.support.deleteExpando){delete a0[a.expando]}else{if(a0.removeAttribute){a0.removeAttribute(a.expando)}}delete aY[a2]}}});a.fn.extend({data:function(aY,a0){if(typeof aY==="undefined"&&this.length){return a.data(this[0])}else{if(typeof aY==="object"){return this.each(function(){a.data(this,aY)})}}var a1=aY.split(".");a1[1]=a1[1]?"."+a1[1]:"";if(a0===C){var aZ=this.triggerHandler("getData"+a1[1]+"!",[a1[0]]);if(aZ===C&&this.length){aZ=a.data(this[0],aY)}return aZ===C&&a1[1]?this.data(a1[0]):aZ}else{return this.trigger("setData"+a1[1]+"!",[a1[0],a0]).each(function(){a.data(this,aY,a0)})}},removeData:function(aY){return this.each(function(){a.removeData(this,aY)})}});a.extend({queue:function(aZ,aY,a1){if(!aZ){return}aY=(aY||"fx")+"queue";var a0=a.data(aZ,aY);if(!a1){return a0||[]}if(!a0||a.isArray(a1)){a0=a.data(aZ,aY,a.makeArray(a1))}else{a0.push(a1)}return a0},dequeue:function(a1,a0){a0=a0||"fx";var aY=a.queue(a1,a0),aZ=aY.shift();if(aZ==="inprogress"){aZ=aY.shift()}if(aZ){if(a0==="fx"){aY.unshift("inprogress")}aZ.call(a1,function(){a.dequeue(a1,a0)})}}});a.fn.extend({queue:function(aY,aZ){if(typeof aY!=="string"){aZ=aY;aY="fx"}if(aZ===C){return a.queue(this[0],aY)}return this.each(function(a1,a2){var a0=a.queue(this,aY,aZ);if(aY==="fx"&&a0[0]!=="inprogress"){a.dequeue(this,aY)}})},dequeue:function(aY){return this.each(function(){a.dequeue(this,aY)})},delay:function(aZ,aY){aZ=a.fx?a.fx.speeds[aZ]||aZ:aZ;aY=aY||"fx";return this.queue(aY,function(){var a0=this;setTimeout(function(){a.dequeue(a0,aY)},aZ)})},clearQueue:function(aY){return this.queue(aY||"fx",[])}});var ao=/[\n\t]/g,S=/\s+/,av=/\r/g,aQ=/href|src|style/,d=/(button|input)/i,z=/(button|input|object|select|textarea)/i,j=/^(a|area)$/i,I=/radio|checkbox/;a.fn.extend({attr:function(aY,aZ){return an(this,aY,aZ,true,a.attr)},removeAttr:function(aY,aZ){return this.each(function(){a.attr(this,aY,"");if(this.nodeType===1){this.removeAttribute(aY)}})},addClass:function(a5){if(a.isFunction(a5)){return this.each(function(a8){var a7=a(this);a7.addClass(a5.call(this,a8,a7.attr("class")))})}if(a5&&typeof a5==="string"){var aY=(a5||"").split(S);for(var a1=0,a0=this.length;a1<a0;a1++){var aZ=this[a1];if(aZ.nodeType===1){if(!aZ.className){aZ.className=a5}else{var a2=" "+aZ.className+" ",a4=aZ.className;for(var a3=0,a6=aY.length;a3<a6;a3++){if(a2.indexOf(" "+aY[a3]+" ")<0){a4+=" "+aY[a3]}}aZ.className=a.trim(a4)}}}}return this},removeClass:function(a3){if(a.isFunction(a3)){return this.each(function(a7){var a6=a(this);a6.removeClass(a3.call(this,a7,a6.attr("class")))})}if((a3&&typeof a3==="string")||a3===C){var a4=(a3||"").split(S);for(var a0=0,aZ=this.length;a0<aZ;a0++){var a2=this[a0];if(a2.nodeType===1&&a2.className){if(a3){var a1=(" "+a2.className+" ").replace(ao," ");for(var a5=0,aY=a4.length;a5<aY;a5++){a1=a1.replace(" "+a4[a5]+" "," ")}a2.className=a.trim(a1)}else{a2.className=""}}}}return this},toggleClass:function(a1,aZ){var a0=typeof a1,aY=typeof aZ==="boolean";if(a.isFunction(a1)){return this.each(function(a3){var a2=a(this);a2.toggleClass(a1.call(this,a3,a2.attr("class"),aZ),aZ)})}return this.each(function(){if(a0==="string"){var a4,a3=0,a2=a(this),a5=aZ,a6=a1.split(S);while((a4=a6[a3++])){a5=aY?a5:!a2.hasClass(a4);a2[a5?"addClass":"removeClass"](a4)}}else{if(a0==="undefined"||a0==="boolean"){if(this.className){a.data(this,"__className__",this.className)}this.className=this.className||a1===false?"":a.data(this,"__className__")||""}}})},hasClass:function(aY){var a1=" "+aY+" ";for(var a0=0,aZ=this.length;a0<aZ;a0++){if((" "+this[a0].className+" ").replace(ao," ").indexOf(a1)>-1){return true}}return false},val:function(a5){if(a5===C){var aZ=this[0];if(aZ){if(a.nodeName(aZ,"option")){return(aZ.attributes.value||{}).specified?aZ.value:aZ.text}if(a.nodeName(aZ,"select")){var a3=aZ.selectedIndex,a6=[],a7=aZ.options,a2=aZ.type==="select-one";if(a3<0){return null}for(var a0=a2?a3:0,a4=a2?a3+1:a7.length;a0<a4;a0++){var a1=a7[a0];if(a1.selected){a5=a(a1).val();if(a2){return a5}a6.push(a5)}}return a6}if(I.test(aZ.type)&&!a.support.checkOn){return aZ.getAttribute("value")===null?"on":aZ.value}return(aZ.value||"").replace(av,"")}return C}var aY=a.isFunction(a5);return this.each(function(ba){var a9=a(this),bb=a5;if(this.nodeType!==1){return}if(aY){bb=a5.call(this,ba,a9.val())}if(typeof bb==="number"){bb+=""}if(a.isArray(bb)&&I.test(this.type)){this.checked=a.inArray(a9.val(),bb)>=0}else{if(a.nodeName(this,"select")){var a8=a.makeArray(bb);a("option",this).each(function(){this.selected=a.inArray(a(this).val(),a8)>=0});if(!a8.length){this.selectedIndex=-1}}else{this.value=bb}}})}});a.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(aZ,aY,a4,a7){if(!aZ||aZ.nodeType===3||aZ.nodeType===8){return C}if(a7&&aY in a.attrFn){return a(aZ)[aY](a4)}var a0=aZ.nodeType!==1||!a.isXMLDoc(aZ),a3=a4!==C;aY=a0&&a.props[aY]||aY;if(aZ.nodeType===1){var a2=aQ.test(aY);if(aY==="selected"&&!a.support.optSelected){var a5=aZ.parentNode;if(a5){a5.selectedIndex;if(a5.parentNode){a5.parentNode.selectedIndex}}}if(aY in aZ&&a0&&!a2){if(a3){if(aY==="type"&&d.test(aZ.nodeName)&&aZ.parentNode){a.error("type property can't be changed")}aZ[aY]=a4}if(a.nodeName(aZ,"form")&&aZ.getAttributeNode(aY)){return aZ.getAttributeNode(aY).nodeValue}if(aY==="tabIndex"){var a6=aZ.getAttributeNode("tabIndex");return a6&&a6.specified?a6.value:z.test(aZ.nodeName)||j.test(aZ.nodeName)&&aZ.href?0:C}return aZ[aY]}if(!a.support.style&&a0&&aY==="style"){if(a3){aZ.style.cssText=""+a4}return aZ.style.cssText}if(a3){aZ.setAttribute(aY,""+a4)}var a1=!a.support.hrefNormalized&&a0&&a2?aZ.getAttribute(aY,2):aZ.getAttribute(aY);return a1===null?C:a1}return a.style(aZ,aY,a4)}});var aC=/\.(.*)$/,A=function(aY){return aY.replace(/[^\w\s\.\|`]/g,function(aZ){return"\\"+aZ})};a.event={add:function(a1,a5,ba,a3){if(a1.nodeType===3||a1.nodeType===8){return}if(a1.setInterval&&(a1!==aM&&!a1.frameElement)){a1=aM}var aZ,a9;if(ba.handler){aZ=ba;ba=aZ.handler}if(!ba.guid){ba.guid=a.guid++}var a6=a.data(a1);if(!a6){return}var bb=a6.events=a6.events||{},a4=a6.handle,a4;if(!a4){a6.handle=a4=function(){return typeof a!=="undefined"&&!a.event.triggered?a.event.handle.apply(a4.elem,arguments):C}}a4.elem=a1;a5=a5.split(" ");var a8,a2=0,aY;while((a8=a5[a2++])){a9=aZ?a.extend({},aZ):{handler:ba,data:a3};if(a8.indexOf(".")>-1){aY=a8.split(".");a8=aY.shift();a9.namespace=aY.slice(0).sort().join(".")}else{aY=[];a9.namespace=""}a9.type=a8;a9.guid=ba.guid;var a0=bb[a8],a7=a.event.special[a8]||{};if(!a0){a0=bb[a8]=[];if(!a7.setup||a7.setup.call(a1,a3,aY,a4)===false){if(a1.addEventListener){a1.addEventListener(a8,a4,false)}else{if(a1.attachEvent){a1.attachEvent("on"+a8,a4)}}}}if(a7.add){a7.add.call(a1,a9);if(!a9.handler.guid){a9.handler.guid=ba.guid}}a0.push(a9);a.event.global[a8]=true}a1=null},global:{},remove:function(bd,a8,aZ,a4){if(bd.nodeType===3||bd.nodeType===8){return}var bg,a3,a5,bb=0,a1,a6,a9,a2,a7,aY,bf,bc=a.data(bd),a0=bc&&bc.events;if(!bc||!a0){return}if(a8&&a8.type){aZ=a8.handler;a8=a8.type}if(!a8||typeof a8==="string"&&a8.charAt(0)==="."){a8=a8||"";for(a3 in a0){a.event.remove(bd,a3+a8)}return}a8=a8.split(" ");while((a3=a8[bb++])){bf=a3;aY=null;a1=a3.indexOf(".")<0;a6=[];if(!a1){a6=a3.split(".");a3=a6.shift();a9=new RegExp("(^|\\.)"+a.map(a6.slice(0).sort(),A).join("\\.(?:.*\\.)?")+"(\\.|$)")}a7=a0[a3];if(!a7){continue}if(!aZ){for(var ba=0;ba<a7.length;ba++){aY=a7[ba];if(a1||a9.test(aY.namespace)){a.event.remove(bd,bf,aY.handler,ba);a7.splice(ba--,1)}}continue}a2=a.event.special[a3]||{};for(var ba=a4||0;ba<a7.length;ba++){aY=a7[ba];if(aZ.guid===aY.guid){if(a1||a9.test(aY.namespace)){if(a4==null){a7.splice(ba--,1)}if(a2.remove){a2.remove.call(bd,aY)}}if(a4!=null){break}}}if(a7.length===0||a4!=null&&a7.length===1){if(!a2.teardown||a2.teardown.call(bd,a6)===false){ag(bd,a3,bc.handle)}bg=null;delete a0[a3]}}if(a.isEmptyObject(a0)){var be=bc.handle;if(be){be.elem=null}delete bc.events;delete bc.handle;if(a.isEmptyObject(bc)){a.removeData(bd)}}},trigger:function(aY,a2,a0){var a7=aY.type||aY,a1=arguments[3];if(!a1){aY=typeof aY==="object"?aY[aI]?aY:a.extend(a.Event(a7),aY):a.Event(a7);if(a7.indexOf("!")>=0){aY.type=a7=a7.slice(0,-1);aY.exclusive=true}if(!a0){aY.stopPropagation();if(a.event.global[a7]){a.each(a.cache,function(){if(this.events&&this.events[a7]){a.event.trigger(aY,a2,this.handle.elem)}})}}if(!a0||a0.nodeType===3||a0.nodeType===8){return C}aY.result=C;aY.target=a0;a2=a.makeArray(a2);a2.unshift(aY)}aY.currentTarget=a0;var a3=a.data(a0,"handle");if(a3){a3.apply(a0,a2)}var a8=a0.parentNode||a0.ownerDocument;try{if(!(a0&&a0.nodeName&&a.noData[a0.nodeName.toLowerCase()])){if(a0["on"+a7]&&a0["on"+a7].apply(a0,a2)===false){aY.result=false}}}catch(a5){}if(!aY.isPropagationStopped()&&a8){a.event.trigger(aY,a2,a8,true)}else{if(!aY.isDefaultPrevented()){var a4=aY.target,aZ,a9=a.nodeName(a4,"a")&&a7==="click",a6=a.event.special[a7]||{};if((!a6._default||a6._default.call(a0,aY)===false)&&!a9&&!(a4&&a4.nodeName&&a.noData[a4.nodeName.toLowerCase()])){try{if(a4[a7]){aZ=a4["on"+a7];if(aZ){a4["on"+a7]=null}a.event.triggered=true;a4[a7]()}}catch(a5){}if(aZ){a4["on"+a7]=aZ}a.event.triggered=false}}}},handle:function(aY){var a6,a0,aZ,a1,a7;aY=arguments[0]=a.event.fix(aY||aM.event);aY.currentTarget=this;a6=aY.type.indexOf(".")<0&&!aY.exclusive;if(!a6){aZ=aY.type.split(".");aY.type=aZ.shift();a1=new RegExp("(^|\\.)"+aZ.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}var a7=a.data(this,"events"),a0=a7[aY.type];if(a7&&a0){a0=a0.slice(0);for(var a3=0,a2=a0.length;a3<a2;a3++){var a5=a0[a3];if(a6||a1.test(a5.namespace)){aY.handler=a5.handler;aY.data=a5.data;aY.handleObj=a5;var a4=a5.handler.apply(this,arguments);if(a4!==C){aY.result=a4;if(a4===false){aY.preventDefault();aY.stopPropagation()}}if(aY.isImmediatePropagationStopped()){break}}}}return aY.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(a1){if(a1[aI]){return a1}var aZ=a1;a1=a.Event(aZ);for(var a0=this.props.length,a3;a0;){a3=this.props[--a0];a1[a3]=aZ[a3]}if(!a1.target){a1.target=a1.srcElement||ab}if(a1.target.nodeType===3){a1.target=a1.target.parentNode}if(!a1.relatedTarget&&a1.fromElement){a1.relatedTarget=a1.fromElement===a1.target?a1.toElement:a1.fromElement}if(a1.pageX==null&&a1.clientX!=null){var a2=ab.documentElement,aY=ab.body;a1.pageX=a1.clientX+(a2&&a2.scrollLeft||aY&&aY.scrollLeft||0)-(a2&&a2.clientLeft||aY&&aY.clientLeft||0);a1.pageY=a1.clientY+(a2&&a2.scrollTop||aY&&aY.scrollTop||0)-(a2&&a2.clientTop||aY&&aY.clientTop||0)}if(!a1.which&&((a1.charCode||a1.charCode===0)?a1.charCode:a1.keyCode)){a1.which=a1.charCode||a1.keyCode}if(!a1.metaKey&&a1.ctrlKey){a1.metaKey=a1.ctrlKey}if(!a1.which&&a1.button!==C){a1.which=(a1.button&1?1:(a1.button&2?3:(a1.button&4?2:0)))}return a1},guid:100000000,proxy:a.proxy,special:{ready:{setup:a.bindReady,teardown:a.noop},live:{add:function(aY){a.event.add(this,aY.origType,a.extend({},aY,{handler:V}))},remove:function(aZ){var aY=true,a0=aZ.origType.replace(aC,"");a.each(a.data(this,"events").live||[],function(){if(a0===this.origType.replace(aC,"")){aY=false;return false}});if(aY){a.event.remove(this,aZ.origType,V)}}},beforeunload:{setup:function(a0,aZ,aY){if(this.setInterval){this.onbeforeunload=aY}return false},teardown:function(aZ,aY){if(this.onbeforeunload===aY){this.onbeforeunload=null}}}}};var ag=ab.removeEventListener?function(aZ,aY,a0){aZ.removeEventListener(aY,a0,false)}:function(aZ,aY,a0){aZ.detachEvent("on"+aY,a0)};a.Event=function(aY){if(!this.preventDefault){return new a.Event(aY)}if(aY&&aY.type){this.originalEvent=aY;this.type=aY.type}else{this.type=aY}this.timeStamp=aP();this[aI]=true};function aR(){return false}function f(){return true}a.Event.prototype={preventDefault:function(){this.isDefaultPrevented=f;var aY=this.originalEvent;if(!aY){return}if(aY.preventDefault){aY.preventDefault()}aY.returnValue=false},stopPropagation:function(){this.isPropagationStopped=f;var aY=this.originalEvent;if(!aY){return}if(aY.stopPropagation){aY.stopPropagation()}aY.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=f;this.stopPropagation()},isDefaultPrevented:aR,isPropagationStopped:aR,isImmediatePropagationStopped:aR};var Q=function(aZ){var aY=aZ.relatedTarget;try{while(aY&&aY!==this){aY=aY.parentNode}if(aY!==this){aZ.type=aZ.data;a.event.handle.apply(this,arguments)}}catch(a0){}},ay=function(aY){aY.type=aY.data;a.event.handle.apply(this,arguments)};a.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(aZ,aY){a.event.special[aZ]={setup:function(a0){a.event.add(this,aY,a0&&a0.selector?ay:Q,aZ)},teardown:function(a0){a.event.remove(this,aY,a0&&a0.selector?ay:Q)}}});if(!a.support.submitBubbles){a.event.special.submit={setup:function(aZ,aY){if(this.nodeName.toLowerCase()!=="form"){a.event.add(this,"click.specialSubmit",function(a2){var a1=a2.target,a0=a1.type;if((a0==="submit"||a0==="image")&&a(a1).closest("form").length){return aA("submit",this,arguments)}});a.event.add(this,"keypress.specialSubmit",function(a2){var a1=a2.target,a0=a1.type;if((a0==="text"||a0==="password")&&a(a1).closest("form").length&&a2.keyCode===13){return aA("submit",this,arguments)}})}else{return false}},teardown:function(aY){a.event.remove(this,".specialSubmit")}}}if(!a.support.changeBubbles){var aq=/textarea|input|select/i,aS,i=function(aZ){var aY=aZ.type,a0=aZ.value;if(aY==="radio"||aY==="checkbox"){a0=aZ.checked}else{if(aY==="select-multiple"){a0=aZ.selectedIndex>-1?a.map(aZ.options,function(a1){return a1.selected}).join("-"):""}else{if(aZ.nodeName.toLowerCase()==="select"){a0=aZ.selectedIndex}}}return a0},O=function O(a0){var aY=a0.target,aZ,a1;if(!aq.test(aY.nodeName)||aY.readOnly){return}aZ=a.data(aY,"_change_data");a1=i(aY);if(a0.type!=="focusout"||aY.type!=="radio"){a.data(aY,"_change_data",a1)}if(aZ===C||a1===aZ){return}if(aZ!=null||a1){a0.type="change";return a.event.trigger(a0,arguments[1],aY)}};a.event.special.change={filters:{focusout:O,click:function(a0){var aZ=a0.target,aY=aZ.type;if(aY==="radio"||aY==="checkbox"||aZ.nodeName.toLowerCase()==="select"){return O.call(this,a0)}},keydown:function(a0){var aZ=a0.target,aY=aZ.type;if((a0.keyCode===13&&aZ.nodeName.toLowerCase()!=="textarea")||(a0.keyCode===32&&(aY==="checkbox"||aY==="radio"))||aY==="select-multiple"){return O.call(this,a0)}},beforeactivate:function(aZ){var aY=aZ.target;a.data(aY,"_change_data",i(aY))}},setup:function(a0,aZ){if(this.type==="file"){return false}for(var aY in aS){a.event.add(this,aY+".specialChange",aS[aY])}return aq.test(this.nodeName)},teardown:function(aY){a.event.remove(this,".specialChange");return aq.test(this.nodeName)}};aS=a.event.special.change.filters}function aA(aZ,a0,aY){aY[0].type=aZ;return a.event.handle.apply(a0,aY)}if(ab.addEventListener){a.each({focus:"focusin",blur:"focusout"},function(a0,aY){a.event.special[aY]={setup:function(){this.addEventListener(a0,aZ,true)},teardown:function(){this.removeEventListener(a0,aZ,true)}};function aZ(a1){a1=a.event.fix(a1);a1.type=aY;return a.event.handle.call(this,a1)}})}a.each(["bind","one"],function(aZ,aY){a.fn[aY]=function(a5,a6,a4){if(typeof a5==="object"){for(var a2 in a5){this[aY](a2,a6,a5[a2],a4)}return this}if(a.isFunction(a6)){a4=a6;a6=C}var a3=aY==="one"?a.proxy(a4,function(a7){a(this).unbind(a7,a3);return a4.apply(this,arguments)}):a4;if(a5==="unload"&&aY!=="one"){this.one(a5,a6,a4)}else{for(var a1=0,a0=this.length;a1<a0;a1++){a.event.add(this[a1],a5,a3,a6)}}return this}});a.fn.extend({unbind:function(a2,a1){if(typeof a2==="object"&&!a2.preventDefault){for(var a0 in a2){this.unbind(a0,a2[a0])}}else{for(var aZ=0,aY=this.length;aZ<aY;aZ++){a.event.remove(this[aZ],a2,a1)}}return this},delegate:function(aY,aZ,a1,a0){return this.live(aZ,a1,a0,aY)},undelegate:function(aY,aZ,a0){if(arguments.length===0){return this.unbind("live")}else{return this.die(aZ,null,a0,aY)}},trigger:function(aY,aZ){return this.each(function(){a.event.trigger(aY,aZ,this)})},triggerHandler:function(aY,a0){if(this[0]){var aZ=a.Event(aY);aZ.preventDefault();aZ.stopPropagation();a.event.trigger(aZ,a0,this[0]);return aZ.result}},toggle:function(a0){var aY=arguments,aZ=1;while(aZ<aY.length){a.proxy(a0,aY[aZ++])}return this.click(a.proxy(a0,function(a1){var a2=(a.data(this,"lastToggle"+a0.guid)||0)%aZ;a.data(this,"lastToggle"+a0.guid,a2+1);a1.preventDefault();return aY[a2].apply(this,arguments)||false}))},hover:function(aY,aZ){return this.mouseenter(aY).mouseleave(aZ||aY)}});var aw={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};a.each(["live","die"],function(aZ,aY){a.fn[aY]=function(a7,a4,a9,a2){var a8,a5=0,a6,a1,ba,a3=a2||this.selector,a0=a2?this:a(this.context);if(a.isFunction(a4)){a9=a4;a4=C}a7=(a7||"").split(" ");while((a8=a7[a5++])!=null){a6=aC.exec(a8);a1="";if(a6){a1=a6[0];a8=a8.replace(aC,"")}if(a8==="hover"){a7.push("mouseenter"+a1,"mouseleave"+a1);continue}ba=a8;if(a8==="focus"||a8==="blur"){a7.push(aw[a8]+a1);a8=a8+a1}else{a8=(aw[a8]||a8)+a1}if(aY==="live"){a0.each(function(){a.event.add(this,m(a8,a3),{data:a4,selector:a3,handler:a9,origType:a8,origHandler:a9,preType:ba})})}else{a0.unbind(m(a8,a3),a9)}}return this}});function V(aY){var a8,aZ=[],bb=[],a7=arguments,ba,a6,a9,a1,a3,a5,a2,a4,bc=a.data(this,"events");if(aY.liveFired===this||!bc||!bc.live||aY.button&&aY.type==="click"){return}aY.liveFired=this;var a0=bc.live.slice(0);for(a3=0;a3<a0.length;a3++){a9=a0[a3];if(a9.origType.replace(aC,"")===aY.type){bb.push(a9.selector)}else{a0.splice(a3--,1)}}a6=a(aY.target).closest(bb,aY.currentTarget);for(a5=0,a2=a6.length;a5<a2;a5++){for(a3=0;a3<a0.length;a3++){a9=a0[a3];if(a6[a5].selector===a9.selector){a1=a6[a5].elem;ba=null;if(a9.preType==="mouseenter"||a9.preType==="mouseleave"){ba=a(aY.relatedTarget).closest(a9.selector)[0]}if(!ba||ba!==a1){aZ.push({elem:a1,handleObj:a9})}}}}for(a5=0,a2=aZ.length;a5<a2;a5++){a6=aZ[a5];aY.currentTarget=a6.elem;aY.data=a6.handleObj.data;aY.handleObj=a6.handleObj;if(a6.handleObj.origHandler.apply(a6.elem,a7)===false){a8=false;break}}return a8}function m(aZ,aY){return"live."+(aZ&&aZ!=="*"?aZ+".":"")+aY.replace(/\./g,"`").replace(/ /g,"&")}a.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(aZ,aY){a.fn[aY]=function(a0){return a0?this.bind(aY,a0):this.trigger(aY)};if(a.attrFn){a.attrFn[aY]=true}});if(aM.attachEvent&&!aM.addEventListener){aM.attachEvent("onunload",function(){for(var aZ in a.cache){if(a.cache[aZ].handle){try{a.event.remove(a.cache[aZ].handle.elem)}catch(aY){}}}});
/*!
* 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 a9=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,ba=0,bc=Object.prototype.toString,a4=false,a3=true;[0,0].sort(function(){a3=false;return 0});var a0=function(bl,bg,bo,bp){bo=bo||[];var br=bg=bg||ab;if(bg.nodeType!==1&&bg.nodeType!==9){return[]}if(!bl||typeof bl!=="string"){return bo}var bm=[],bi,bt,bw,bh,bk=true,bj=a1(bg),bq=bl;while((a9.exec(""),bi=a9.exec(bq))!==null){bq=bi[3];bm.push(bi[1]);if(bi[2]){bh=bi[3];break}}if(bm.length>1&&a5.exec(bl)){if(bm.length===2&&a6.relative[bm[0]]){bt=bd(bm[0]+bm[1],bg)}else{bt=a6.relative[bm[0]]?[bg]:a0(bm.shift(),bg);while(bm.length){bl=bm.shift();if(a6.relative[bl]){bl+=bm.shift()}bt=bd(bl,bt)}}}else{if(!bp&&bm.length>1&&bg.nodeType===9&&!bj&&a6.match.ID.test(bm[0])&&!a6.match.ID.test(bm[bm.length-1])){var bs=a0.find(bm.shift(),bg,bj);bg=bs.expr?a0.filter(bs.expr,bs.set)[0]:bs.set[0]}if(bg){var bs=bp?{expr:bm.pop(),set:a8(bp)}:a0.find(bm.pop(),bm.length===1&&(bm[0]==="~"||bm[0]==="+")&&bg.parentNode?bg.parentNode:bg,bj);bt=bs.expr?a0.filter(bs.expr,bs.set):bs.set;if(bm.length>0){bw=a8(bt)}else{bk=false}while(bm.length){var bv=bm.pop(),bu=bv;if(!a6.relative[bv]){bv=""}else{bu=bm.pop()}if(bu==null){bu=bg}a6.relative[bv](bw,bu,bj)}}else{bw=bm=[]}}if(!bw){bw=bt}if(!bw){a0.error(bv||bl)}if(bc.call(bw)==="[object Array]"){if(!bk){bo.push.apply(bo,bw)}else{if(bg&&bg.nodeType===1){for(var bn=0;bw[bn]!=null;bn++){if(bw[bn]&&(bw[bn]===true||bw[bn].nodeType===1&&a7(bg,bw[bn]))){bo.push(bt[bn])}}}else{for(var bn=0;bw[bn]!=null;bn++){if(bw[bn]&&bw[bn].nodeType===1){bo.push(bt[bn])}}}}}else{a8(bw,bo)}if(bh){a0(bh,br,bo,bp);a0.uniqueSort(bo)}return bo};a0.uniqueSort=function(bh){if(bb){a4=a3;bh.sort(bb);if(a4){for(var bg=1;bg<bh.length;bg++){if(bh[bg]===bh[bg-1]){bh.splice(bg--,1)}}}}return bh};a0.matches=function(bg,bh){return a0(bg,null,null,bh)};a0.find=function(bn,bg,bo){var bm,bk;if(!bn){return[]}for(var bj=0,bi=a6.order.length;bj<bi;bj++){var bl=a6.order[bj],bk;if((bk=a6.leftMatch[bl].exec(bn))){var bh=bk[1];bk.splice(1,1);if(bh.substr(bh.length-1)!=="\\"){bk[1]=(bk[1]||"").replace(/\\/g,"");bm=a6.find[bl](bk,bg,bo);if(bm!=null){bn=bn.replace(a6.match[bl],"");break}}}}if(!bm){bm=bg.getElementsByTagName("*")}return{set:bm,expr:bn}};a0.filter=function(br,bq,bu,bk){var bi=br,bw=[],bo=bq,bm,bg,bn=bq&&bq[0]&&a1(bq[0]);while(br&&bq.length){for(var bp in a6.filter){if((bm=a6.leftMatch[bp].exec(br))!=null&&bm[2]){var bh=a6.filter[bp],bv,bt,bj=bm[1];bg=false;bm.splice(1,1);if(bj.substr(bj.length-1)==="\\"){continue}if(bo===bw){bw=[]}if(a6.preFilter[bp]){bm=a6.preFilter[bp](bm,bo,bu,bw,bk,bn);if(!bm){bg=bv=true}else{if(bm===true){continue}}}if(bm){for(var bl=0;(bt=bo[bl])!=null;bl++){if(bt){bv=bh(bt,bm,bl,bo);var bs=bk^!!bv;if(bu&&bv!=null){if(bs){bg=true}else{bo[bl]=false}}else{if(bs){bw.push(bt);bg=true}}}}}if(bv!==C){if(!bu){bo=bw}br=br.replace(a6.match[bp],"");if(!bg){return[]}break}}}if(br===bi){if(bg==null){a0.error(br)}else{break}}bi=br}return bo};a0.error=function(bg){throw"Syntax error, unrecognized expression: "+bg};var a6=a0.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(bg){return bg.getAttribute("href")}},relative:{"+":function(bm,bh){var bj=typeof bh==="string",bl=bj&&!/\W/.test(bh),bn=bj&&!bl;if(bl){bh=bh.toLowerCase()}for(var bi=0,bg=bm.length,bk;bi<bg;bi++){if((bk=bm[bi])){while((bk=bk.previousSibling)&&bk.nodeType!==1){}bm[bi]=bn||bk&&bk.nodeName.toLowerCase()===bh?bk||false:bk===bh}}if(bn){a0.filter(bh,bm,true)}},">":function(bm,bh){var bk=typeof bh==="string";if(bk&&!/\W/.test(bh)){bh=bh.toLowerCase();for(var bi=0,bg=bm.length;bi<bg;bi++){var bl=bm[bi];if(bl){var bj=bl.parentNode;bm[bi]=bj.nodeName.toLowerCase()===bh?bj:false}}}else{for(var bi=0,bg=bm.length;bi<bg;bi++){var bl=bm[bi];if(bl){bm[bi]=bk?bl.parentNode:bl.parentNode===bh}}if(bk){a0.filter(bh,bm,true)}}},"":function(bj,bh,bl){var bi=ba++,bg=be;if(typeof bh==="string"&&!/\W/.test(bh)){var bk=bh=bh.toLowerCase();bg=aY}bg("parentNode",bh,bi,bj,bk,bl)},"~":function(bj,bh,bl){var bi=ba++,bg=be;if(typeof bh==="string"&&!/\W/.test(bh)){var bk=bh=bh.toLowerCase();bg=aY}bg("previousSibling",bh,bi,bj,bk,bl)}},find:{ID:function(bh,bi,bj){if(typeof bi.getElementById!=="undefined"&&!bj){var bg=bi.getElementById(bh[1]);return bg?[bg]:[]}},NAME:function(bi,bl){if(typeof bl.getElementsByName!=="undefined"){var bh=[],bk=bl.getElementsByName(bi[1]);for(var bj=0,bg=bk.length;bj<bg;bj++){if(bk[bj].getAttribute("name")===bi[1]){bh.push(bk[bj])}}return bh.length===0?null:bh}},TAG:function(bg,bh){return bh.getElementsByTagName(bg[1])}},preFilter:{CLASS:function(bj,bh,bi,bg,bm,bn){bj=" "+bj[1].replace(/\\/g,"")+" ";if(bn){return bj}for(var bk=0,bl;(bl=bh[bk])!=null;bk++){if(bl){if(bm^(bl.className&&(" "+bl.className+" ").replace(/[\t\n]/g," ").indexOf(bj)>=0)){if(!bi){bg.push(bl)}}else{if(bi){bh[bk]=false}}}}return false},ID:function(bg){return bg[1].replace(/\\/g,"")},TAG:function(bh,bg){return bh[1].toLowerCase()},CHILD:function(bg){if(bg[1]==="nth"){var bh=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(bg[2]==="even"&&"2n"||bg[2]==="odd"&&"2n+1"||!/\D/.test(bg[2])&&"0n+"+bg[2]||bg[2]);bg[2]=(bh[1]+(bh[2]||1))-0;bg[3]=bh[3]-0}bg[0]=ba++;return bg},ATTR:function(bk,bh,bi,bg,bl,bm){var bj=bk[1].replace(/\\/g,"");if(!bm&&a6.attrMap[bj]){bk[1]=a6.attrMap[bj]}if(bk[2]==="~="){bk[4]=" "+bk[4]+" "}return bk},PSEUDO:function(bk,bh,bi,bg,bl){if(bk[1]==="not"){if((a9.exec(bk[3])||"").length>1||/^\w/.test(bk[3])){bk[3]=a0(bk[3],null,null,bh)}else{var bj=a0.filter(bk[3],bh,bi,true^bl);if(!bi){bg.push.apply(bg,bj)}return false}}else{if(a6.match.POS.test(bk[0])||a6.match.CHILD.test(bk[0])){return true}}return bk},POS:function(bg){bg.unshift(true);return bg}},filters:{enabled:function(bg){return bg.disabled===false&&bg.type!=="hidden"},disabled:function(bg){return bg.disabled===true},checked:function(bg){return bg.checked===true},selected:function(bg){bg.parentNode.selectedIndex;return bg.selected===true},parent:function(bg){return !!bg.firstChild},empty:function(bg){return !bg.firstChild},has:function(bi,bh,bg){return !!a0(bg[3],bi).length},header:function(bg){return/h\d/i.test(bg.nodeName)},text:function(bg){return"text"===bg.type},radio:function(bg){return"radio"===bg.type},checkbox:function(bg){return"checkbox"===bg.type},file:function(bg){return"file"===bg.type},password:function(bg){return"password"===bg.type},submit:function(bg){return"submit"===bg.type},image:function(bg){return"image"===bg.type},reset:function(bg){return"reset"===bg.type},button:function(bg){return"button"===bg.type||bg.nodeName.toLowerCase()==="button"},input:function(bg){return/input|select|textarea|button/i.test(bg.nodeName)}},setFilters:{first:function(bh,bg){return bg===0},last:function(bi,bh,bg,bj){return bh===bj.length-1},even:function(bh,bg){return bg%2===0},odd:function(bh,bg){return bg%2===1},lt:function(bi,bh,bg){return bh<bg[3]-0},gt:function(bi,bh,bg){return bh>bg[3]-0},nth:function(bi,bh,bg){return bg[3]-0===bh},eq:function(bi,bh,bg){return bg[3]-0===bh}},filter:{PSEUDO:function(bm,bi,bj,bn){var bh=bi[1],bk=a6.filters[bh];if(bk){return bk(bm,bj,bi,bn)}else{if(bh==="contains"){return(bm.textContent||bm.innerText||aZ([bm])||"").indexOf(bi[3])>=0}else{if(bh==="not"){var bl=bi[3];for(var bj=0,bg=bl.length;bj<bg;bj++){if(bl[bj]===bm){return false}}return true}else{a0.error("Syntax error, unrecognized expression: "+bh)}}}},CHILD:function(bg,bj){var bm=bj[1],bh=bg;switch(bm){case"only":case"first":while((bh=bh.previousSibling)){if(bh.nodeType===1){return false}}if(bm==="first"){return true}bh=bg;case"last":while((bh=bh.nextSibling)){if(bh.nodeType===1){return false}}return true;case"nth":var bi=bj[2],bp=bj[3];if(bi===1&&bp===0){return true}var bl=bj[0],bo=bg.parentNode;if(bo&&(bo.sizcache!==bl||!bg.nodeIndex)){var bk=0;for(bh=bo.firstChild;bh;bh=bh.nextSibling){if(bh.nodeType===1){bh.nodeIndex=++bk}}bo.sizcache=bl}var bn=bg.nodeIndex-bp;if(bi===0){return bn===0}else{return(bn%bi===0&&bn/bi>=0)}}},ID:function(bh,bg){return bh.nodeType===1&&bh.getAttribute("id")===bg},TAG:function(bh,bg){return(bg==="*"&&bh.nodeType===1)||bh.nodeName.toLowerCase()===bg},CLASS:function(bh,bg){return(" "+(bh.className||bh.getAttribute("class"))+" ").indexOf(bg)>-1},ATTR:function(bl,bj){var bi=bj[1],bg=a6.attrHandle[bi]?a6.attrHandle[bi](bl):bl[bi]!=null?bl[bi]:bl.getAttribute(bi),bm=bg+"",bk=bj[2],bh=bj[4];return bg==null?bk==="!=":bk==="="?bm===bh:bk==="*="?bm.indexOf(bh)>=0:bk==="~="?(" "+bm+" ").indexOf(bh)>=0:!bh?bm&&bg!==false:bk==="!="?bm!==bh:bk==="^="?bm.indexOf(bh)===0:bk==="$="?bm.substr(bm.length-bh.length)===bh:bk==="|="?bm===bh||bm.substr(0,bh.length+1)===bh+"-":false},POS:function(bk,bh,bi,bl){var bg=bh[2],bj=a6.setFilters[bg];if(bj){return bj(bk,bi,bh,bl)}}}};var a5=a6.match.POS;for(var a2 in a6.match){a6.match[a2]=new RegExp(a6.match[a2].source+/(?![^\[]*\])(?![^\(]*\))/.source);a6.leftMatch[a2]=new RegExp(/(^(?:.|\r|\n)*?)/.source+a6.match[a2].source.replace(/\\(\d+)/g,function(bh,bg){return"\\"+(bg-0+1)}))}var a8=function(bh,bg){bh=Array.prototype.slice.call(bh,0);if(bg){bg.push.apply(bg,bh);return bg}return bh};try{Array.prototype.slice.call(ab.documentElement.childNodes,0)[0].nodeType}catch(bf){a8=function(bk,bj){var bh=bj||[];if(bc.call(bk)==="[object Array]"){Array.prototype.push.apply(bh,bk)}else{if(typeof bk.length==="number"){for(var bi=0,bg=bk.length;bi<bg;bi++){bh.push(bk[bi])}}else{for(var bi=0;bk[bi];bi++){bh.push(bk[bi])}}}return bh}}var bb;if(ab.documentElement.compareDocumentPosition){bb=function(bh,bg){if(!bh.compareDocumentPosition||!bg.compareDocumentPosition){if(bh==bg){a4=true}return bh.compareDocumentPosition?-1:1}var bi=bh.compareDocumentPosition(bg)&4?-1:bh===bg?0:1;if(bi===0){a4=true}return bi}}else{if("sourceIndex" in ab.documentElement){bb=function(bh,bg){if(!bh.sourceIndex||!bg.sourceIndex){if(bh==bg){a4=true}return bh.sourceIndex?-1:1}var bi=bh.sourceIndex-bg.sourceIndex;if(bi===0){a4=true}return bi}}else{if(ab.createRange){bb=function(bj,bh){if(!bj.ownerDocument||!bh.ownerDocument){if(bj==bh){a4=true}return bj.ownerDocument?-1:1}var bi=bj.ownerDocument.createRange(),bg=bh.ownerDocument.createRange();bi.setStart(bj,0);bi.setEnd(bj,0);bg.setStart(bh,0);bg.setEnd(bh,0);var bk=bi.compareBoundaryPoints(Range.START_TO_END,bg);if(bk===0){a4=true}return bk}}}}function aZ(bg){var bh="",bj;for(var bi=0;bg[bi];bi++){bj=bg[bi];if(bj.nodeType===3||bj.nodeType===4){bh+=bj.nodeValue}else{if(bj.nodeType!==8){bh+=aZ(bj.childNodes)}}}return bh}(function(){var bh=ab.createElement("div"),bi="script"+(new Date).getTime();bh.innerHTML="<a name='"+bi+"'/>";var bg=ab.documentElement;bg.insertBefore(bh,bg.firstChild);if(ab.getElementById(bi)){a6.find.ID=function(bk,bl,bm){if(typeof bl.getElementById!=="undefined"&&!bm){var bj=bl.getElementById(bk[1]);return bj?bj.id===bk[1]||typeof bj.getAttributeNode!=="undefined"&&bj.getAttributeNode("id").nodeValue===bk[1]?[bj]:C:[]}};a6.filter.ID=function(bl,bj){var bk=typeof bl.getAttributeNode!=="undefined"&&bl.getAttributeNode("id");return bl.nodeType===1&&bk&&bk.nodeValue===bj}}bg.removeChild(bh);bg=bh=null})();(function(){var bg=ab.createElement("div");bg.appendChild(ab.createComment(""));if(bg.getElementsByTagName("*").length>0){a6.find.TAG=function(bh,bl){var bk=bl.getElementsByTagName(bh[1]);if(bh[1]==="*"){var bj=[];for(var bi=0;bk[bi];bi++){if(bk[bi].nodeType===1){bj.push(bk[bi])}}bk=bj}return bk}}bg.innerHTML="<a href='#'></a>";if(bg.firstChild&&typeof bg.firstChild.getAttribute!=="undefined"&&bg.firstChild.getAttribute("href")!=="#"){a6.attrHandle.href=function(bh){return bh.getAttribute("href",2)}}bg=null})();if(ab.querySelectorAll){(function(){var bg=a0,bi=ab.createElement("div");bi.innerHTML="<p class='TEST'></p>";if(bi.querySelectorAll&&bi.querySelectorAll(".TEST").length===0){return}a0=function(bm,bl,bj,bk){bl=bl||ab;if(!bk&&bl.nodeType===9&&!a1(bl)){try{return a8(bl.querySelectorAll(bm),bj)}catch(bn){}}return bg(bm,bl,bj,bk)};for(var bh in bg){a0[bh]=bg[bh]}bi=null})()}(function(){var bg=ab.createElement("div");bg.innerHTML="<div class='test e'></div><div class='test'></div>";if(!bg.getElementsByClassName||bg.getElementsByClassName("e").length===0){return}bg.lastChild.className="e";if(bg.getElementsByClassName("e").length===1){return}a6.order.splice(1,0,"CLASS");a6.find.CLASS=function(bh,bi,bj){if(typeof bi.getElementsByClassName!=="undefined"&&!bj){return bi.getElementsByClassName(bh[1])}};bg=null})();function aY(bh,bm,bl,bp,bn,bo){for(var bj=0,bi=bp.length;bj<bi;bj++){var bg=bp[bj];if(bg){bg=bg[bh];var bk=false;while(bg){if(bg.sizcache===bl){bk=bp[bg.sizset];break}if(bg.nodeType===1&&!bo){bg.sizcache=bl;bg.sizset=bj}if(bg.nodeName.toLowerCase()===bm){bk=bg;break}bg=bg[bh]}bp[bj]=bk}}}function be(bh,bm,bl,bp,bn,bo){for(var bj=0,bi=bp.length;bj<bi;bj++){var bg=bp[bj];if(bg){bg=bg[bh];var bk=false;while(bg){if(bg.sizcache===bl){bk=bp[bg.sizset];break}if(bg.nodeType===1){if(!bo){bg.sizcache=bl;bg.sizset=bj}if(typeof bm!=="string"){if(bg===bm){bk=true;break}}else{if(a0.filter(bm,[bg]).length>0){bk=bg;break}}}bg=bg[bh]}bp[bj]=bk}}}var a7=ab.compareDocumentPosition?function(bh,bg){return !!(bh.compareDocumentPosition(bg)&16)}:function(bh,bg){return bh!==bg&&(bh.contains?bh.contains(bg):true)};var a1=function(bg){var bh=(bg?bg.ownerDocument||bg:0).documentElement;return bh?bh.nodeName!=="HTML":false};var bd=function(bg,bn){var bj=[],bk="",bl,bi=bn.nodeType?[bn]:bn;while((bl=a6.match.PSEUDO.exec(bg))){bk+=bl[0];bg=bg.replace(a6.match.PSEUDO,"")}bg=a6.relative[bg]?bg+"*":bg;for(var bm=0,bh=bi.length;bm<bh;bm++){a0(bg,bi[bm],bj)}return a0.filter(bk,bj)};a.find=a0;a.expr=a0.selectors;a.expr[":"]=a.expr.filters;a.unique=a0.uniqueSort;a.text=aZ;a.isXMLDoc=a1;a.contains=a7;return;aM.Sizzle=a0})();var N=/Until$/,Y=/^(?:parents|prevUntil|prevAll)/,aL=/,/,F=Array.prototype.slice;var ai=function(a1,a0,aY){if(a.isFunction(a0)){return a.grep(a1,function(a3,a2){return !!a0.call(a3,a2,a3)===aY})}else{if(a0.nodeType){return a.grep(a1,function(a3,a2){return(a3===a0)===aY})}else{if(typeof a0==="string"){var aZ=a.grep(a1,function(a2){return a2.nodeType===1});if(aW.test(a0)){return a.filter(a0,aZ,!aY)}else{a0=a.filter(a0,aZ)}}}}return a.grep(a1,function(a3,a2){return(a.inArray(a3,a0)>=0)===aY})};a.fn.extend({find:function(aY){var a0=this.pushStack("","find",aY),a3=0;for(var a1=0,aZ=this.length;a1<aZ;a1++){a3=a0.length;a.find(aY,this[a1],a0);if(a1>0){for(var a4=a3;a4<a0.length;a4++){for(var a2=0;a2<a3;a2++){if(a0[a2]===a0[a4]){a0.splice(a4--,1);break}}}}}return a0},has:function(aZ){var aY=a(aZ);return this.filter(function(){for(var a1=0,a0=aY.length;a1<a0;a1++){if(a.contains(this,aY[a1])){return true}}})},not:function(aY){return this.pushStack(ai(this,aY,false),"not",aY)},filter:function(aY){return this.pushStack(ai(this,aY,true),"filter",aY)},is:function(aY){return !!aY&&a.filter(aY,this).length>0},closest:function(a7,aY){if(a.isArray(a7)){var a4=[],a6=this[0],a3,a2={},a0;if(a6&&a7.length){for(var a1=0,aZ=a7.length;a1<aZ;a1++){a0=a7[a1];if(!a2[a0]){a2[a0]=a.expr.match.POS.test(a0)?a(a0,aY||this.context):a0}}while(a6&&a6.ownerDocument&&a6!==aY){for(a0 in a2){a3=a2[a0];if(a3.jquery?a3.index(a6)>-1:a(a6).is(a3)){a4.push({selector:a0,elem:a6});delete a2[a0]}}a6=a6.parentNode}}return a4}var a5=a.expr.match.POS.test(a7)?a(a7,aY||this.context):null;return this.map(function(a8,a9){while(a9&&a9.ownerDocument&&a9!==aY){if(a5?a5.index(a9)>-1:a(a9).is(a7)){return a9}a9=a9.parentNode}return null})},index:function(aY){if(!aY||typeof aY==="string"){return a.inArray(this[0],aY?a(aY):this.parent().children())}return a.inArray(aY.jquery?aY[0]:aY,this)},add:function(aY,aZ){var a1=typeof aY==="string"?a(aY,aZ||this.context):a.makeArray(aY),a0=a.merge(this.get(),a1);return this.pushStack(y(a1[0])||y(a0[0])?a0:a.unique(a0))},andSelf:function(){return this.add(this.prevObject)}});function y(aY){return !aY||!aY.parentNode||aY.parentNode.nodeType===11}a.each({parent:function(aZ){var aY=aZ.parentNode;return aY&&aY.nodeType!==11?aY:null},parents:function(aY){return a.dir(aY,"parentNode")},parentsUntil:function(aZ,aY,a0){return a.dir(aZ,"parentNode",a0)},next:function(aY){return a.nth(aY,2,"nextSibling")},prev:function(aY){return a.nth(aY,2,"previousSibling")},nextAll:function(aY){return a.dir(aY,"nextSibling")},prevAll:function(aY){return a.dir(aY,"previousSibling")},nextUntil:function(aZ,aY,a0){return a.dir(aZ,"nextSibling",a0)},prevUntil:function(aZ,aY,a0){return a.dir(aZ,"previousSibling",a0)},siblings:function(aY){return a.sibling(aY.parentNode.firstChild,aY)},children:function(aY){return a.sibling(aY.firstChild)},contents:function(aY){return a.nodeName(aY,"iframe")?aY.contentDocument||aY.contentWindow.document:a.makeArray(aY.childNodes)}},function(aY,aZ){a.fn[aY]=function(a2,a0){var a1=a.map(this,aZ,a2);if(!N.test(aY)){a0=a2}if(a0&&typeof a0==="string"){a1=a.filter(a0,a1)}a1=this.length>1?a.unique(a1):a1;if((this.length>1||aL.test(a0))&&Y.test(aY)){a1=a1.reverse()}return this.pushStack(a1,aY,F.call(arguments).join(","))}});a.extend({filter:function(a0,aY,aZ){if(aZ){a0=":not("+a0+")"}return a.find.matches(a0,aY)},dir:function(a0,aZ,a2){var aY=[],a1=a0[aZ];while(a1&&a1.nodeType!==9&&(a2===C||a1.nodeType!==1||!a(a1).is(a2))){if(a1.nodeType===1){aY.push(a1)}a1=a1[aZ]}return aY},nth:function(a2,aY,a0,a1){aY=aY||1;var aZ=0;for(;a2;a2=a2[a0]){if(a2.nodeType===1&&++aZ===aY){break}}return a2},sibling:function(a0,aZ){var aY=[];for(;a0;a0=a0.nextSibling){if(a0.nodeType===1&&a0!==aZ){aY.push(a0)}}return aY}});var T=/ jQuery\d+="(?:\d+|null)"/g,Z=/^\s+/,H=/(<([\w:]+)[^>]*?)\/>/g,al=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,c=/<([\w:]+)/,t=/<tbody/i,L=/<|&#?\w+;/,E=/<script|<object|<embed|<option|<style/i,l=/checked\s*(?:[^=]|=\s*.checked.)/i,p=function(aZ,a0,aY){return al.test(aY)?aZ:a0+"></"+aY+">"},ac={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,"",""]};ac.optgroup=ac.option;ac.tbody=ac.tfoot=ac.colgroup=ac.caption=ac.thead;ac.th=ac.td;if(!a.support.htmlSerialize){ac._default=[1,"div<div>","</div>"]}a.fn.extend({text:function(aY){if(a.isFunction(aY)){return this.each(function(a0){var aZ=a(this);aZ.text(aY.call(this,a0,aZ.text()))})}if(typeof aY!=="object"&&aY!==C){return this.empty().append((this[0]&&this[0].ownerDocument||ab).createTextNode(aY))}return a.text(this)},wrapAll:function(aY){if(a.isFunction(aY)){return this.each(function(a0){a(this).wrapAll(aY.call(this,a0))})}if(this[0]){var aZ=a(aY,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){aZ.insertBefore(this[0])}aZ.map(function(){var a0=this;while(a0.firstChild&&a0.firstChild.nodeType===1){a0=a0.firstChild}return a0}).append(this)}return this},wrapInner:function(aY){if(a.isFunction(aY)){return this.each(function(aZ){a(this).wrapInner(aY.call(this,aZ))})}return this.each(function(){var aZ=a(this),a0=aZ.contents();if(a0.length){a0.wrapAll(aY)}else{aZ.append(aY)}})},wrap:function(aY){return this.each(function(){a(this).wrapAll(aY)})},unwrap:function(){return this.parent().each(function(){if(!a.nodeName(this,"body")){a(this).replaceWith(this.childNodes)}}).end()},append:function(){return this.domManip(arguments,true,function(aY){if(this.nodeType===1){this.appendChild(aY)}})},prepend:function(){return this.domManip(arguments,true,function(aY){if(this.nodeType===1){this.insertBefore(aY,this.firstChild)}})},before:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(aZ){this.parentNode.insertBefore(aZ,this)})}else{if(arguments.length){var aY=a(arguments[0]);aY.push.apply(aY,this.toArray());return this.pushStack(aY,"before",arguments)}}},after:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(aZ){this.parentNode.insertBefore(aZ,this.nextSibling)})}else{if(arguments.length){var aY=this.pushStack(this,"after",arguments);aY.push.apply(aY,a(arguments[0]).toArray());return aY}}},remove:function(aY,a1){for(var aZ=0,a0;(a0=this[aZ])!=null;aZ++){if(!aY||a.filter(aY,[a0]).length){if(!a1&&a0.nodeType===1){a.cleanData(a0.getElementsByTagName("*"));a.cleanData([a0])}if(a0.parentNode){a0.parentNode.removeChild(a0)}}}return this},empty:function(){for(var aY=0,aZ;(aZ=this[aY])!=null;aY++){if(aZ.nodeType===1){a.cleanData(aZ.getElementsByTagName("*"))}while(aZ.firstChild){aZ.removeChild(aZ.firstChild)}}return this},clone:function(aZ){var aY=this.map(function(){if(!a.support.noCloneEvent&&!a.isXMLDoc(this)){var a1=this.outerHTML,a0=this.ownerDocument;if(!a1){var a2=a0.createElement("div");a2.appendChild(this.cloneNode(true));a1=a2.innerHTML}return a.clean([a1.replace(T,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(Z,"")],a0)[0]}else{return this.cloneNode(true)}});if(aZ===true){q(this,aY);q(this.find("*"),aY.find("*"))}return aY},html:function(a0){if(a0===C){return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(T,""):null}else{if(typeof a0==="string"&&!E.test(a0)&&(a.support.leadingWhitespace||!Z.test(a0))&&!ac[(c.exec(a0)||["",""])[1].toLowerCase()]){a0=a0.replace(H,p);try{for(var aZ=0,aY=this.length;aZ<aY;aZ++){if(this[aZ].nodeType===1){a.cleanData(this[aZ].getElementsByTagName("*"));this[aZ].innerHTML=a0}}}catch(a1){this.empty().append(a0)}}else{if(a.isFunction(a0)){this.each(function(a4){var a3=a(this),a2=a3.html();a3.empty().append(function(){return a0.call(this,a4,a2)})})}else{this.empty().append(a0)}}}return this},replaceWith:function(aY){if(this[0]&&this[0].parentNode){if(a.isFunction(aY)){return this.each(function(a1){var a0=a(this),aZ=a0.html();a0.replaceWith(aY.call(this,a1,aZ))})}if(typeof aY!=="string"){aY=a(aY).detach()}return this.each(function(){var a0=this.nextSibling,aZ=this.parentNode;a(this).remove();if(a0){a(a0).before(aY)}else{a(aZ).append(aY)}})}else{return this.pushStack(a(a.isFunction(aY)?aY():aY),"replaceWith",aY)}},detach:function(aY){return this.remove(aY,true)},domManip:function(a4,a9,a8){var a1,a2,a7=a4[0],aZ=[],a3,a6;if(!a.support.checkClone&&arguments.length===3&&typeof a7==="string"&&l.test(a7)){return this.each(function(){a(this).domManip(a4,a9,a8,true)})}if(a.isFunction(a7)){return this.each(function(bb){var ba=a(this);a4[0]=a7.call(this,bb,a9?ba.html():C);ba.domManip(a4,a9,a8)})}if(this[0]){a6=a7&&a7.parentNode;if(a.support.parentNode&&a6&&a6.nodeType===11&&a6.childNodes.length===this.length){a1={fragment:a6}}else{a1=J(a4,this,aZ)}a3=a1.fragment;if(a3.childNodes.length===1){a2=a3=a3.firstChild}else{a2=a3.firstChild}if(a2){a9=a9&&a.nodeName(a2,"tr");for(var a0=0,aY=this.length;a0<aY;a0++){a8.call(a9?a5(this[a0],a2):this[a0],a0>0||a1.cacheable||this.length>1?a3.cloneNode(true):a3)}}if(aZ.length){a.each(aZ,aV)}}return this;function a5(ba,bb){return a.nodeName(ba,"table")?(ba.getElementsByTagName("tbody")[0]||ba.appendChild(ba.ownerDocument.createElement("tbody"))):ba}}});function q(a0,aY){var aZ=0;aY.each(function(){if(this.nodeName!==(a0[aZ]&&a0[aZ].nodeName)){return}var a5=a.data(a0[aZ++]),a4=a.data(this,a5),a1=a5&&a5.events;if(a1){delete a4.handle;a4.events={};for(var a3 in a1){for(var a2 in a1[a3]){a.event.add(this,a3,a1[a3][a2],a1[a3][a2].data)}}}})}function J(a3,a1,aZ){var a2,aY,a0,a4=(a1&&a1[0]?a1[0].ownerDocument||a1[0]:ab);if(a3.length===1&&typeof a3[0]==="string"&&a3[0].length<512&&a4===ab&&!E.test(a3[0])&&(a.support.checkClone||!l.test(a3[0]))){aY=true;a0=a.fragments[a3[0]];if(a0){if(a0!==1){a2=a0}}}if(!a2){a2=a4.createDocumentFragment();a.clean(a3,a4,a2,aZ)}if(aY){a.fragments[a3[0]]=a0?a2:1}return{fragment:a2,cacheable:aY}}a.fragments={};a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(aY,aZ){a.fn[aY]=function(a0){var a3=[],a6=a(a0),a5=this.length===1&&this[0].parentNode;if(a5&&a5.nodeType===11&&a5.childNodes.length===1&&a6.length===1){a6[aZ](this[0]);return this}else{for(var a4=0,a1=a6.length;a4<a1;a4++){var a2=(a4>0?this.clone(true):this).get();a.fn[aZ].apply(a(a6[a4]),a2);a3=a3.concat(a2)}return this.pushStack(a3,aY,a6.selector)}}});a.extend({clean:function(a0,a2,a9,a4){a2=a2||ab;if(typeof a2.createElement==="undefined"){a2=a2.ownerDocument||a2[0]&&a2[0].ownerDocument||ab}var ba=[];for(var a8=0,a3;(a3=a0[a8])!=null;a8++){if(typeof a3==="number"){a3+=""}if(!a3){continue}if(typeof a3==="string"&&!L.test(a3)){a3=a2.createTextNode(a3)}else{if(typeof a3==="string"){a3=a3.replace(H,p);var bb=(c.exec(a3)||["",""])[1].toLowerCase(),a1=ac[bb]||ac._default,a7=a1[0],aZ=a2.createElement("div");aZ.innerHTML=a1[1]+a3+a1[2];while(a7--){aZ=aZ.lastChild}if(!a.support.tbody){var aY=t.test(a3),a6=bb==="table"&&!aY?aZ.firstChild&&aZ.firstChild.childNodes:a1[1]==="<table>"&&!aY?aZ.childNodes:[];for(var a5=a6.length-1;a5>=0;--a5){if(a.nodeName(a6[a5],"tbody")&&!a6[a5].childNodes.length){a6[a5].parentNode.removeChild(a6[a5])}}}if(!a.support.leadingWhitespace&&Z.test(a3)){aZ.insertBefore(a2.createTextNode(Z.exec(a3)[0]),aZ.firstChild)}a3=aZ.childNodes}}if(a3.nodeType){ba.push(a3)}else{ba=a.merge(ba,a3)}}if(a9){for(var a8=0;ba[a8];a8++){if(a4&&a.nodeName(ba[a8],"script")&&(!ba[a8].type||ba[a8].type.toLowerCase()==="text/javascript")){a4.push(ba[a8].parentNode?ba[a8].parentNode.removeChild(ba[a8]):ba[a8])}else{if(ba[a8].nodeType===1){ba.splice.apply(ba,[a8+1,0].concat(a.makeArray(ba[a8].getElementsByTagName("script"))))}a9.appendChild(ba[a8])}}}return ba},cleanData:function(aZ){var a2,a0,aY=a.cache,a5=a.event.special,a4=a.support.deleteExpando;for(var a3=0,a1;(a1=aZ[a3])!=null;a3++){a0=a1[a.expando];if(a0){a2=aY[a0];if(a2.events){for(var a6 in a2.events){if(a5[a6]){a.event.remove(a1,a6)}else{ag(a1,a6,a2.handle)}}}if(a4){delete a1[a.expando]}else{if(a1.removeAttribute){a1.removeAttribute(a.expando)}}delete aY[a0]}}}});var ar=/z-?index|font-?weight|opacity|zoom|line-?height/i,U=/alpha\([^)]*\)/,aa=/opacity=([^)]*)/,ah=/float/i,az=/-([a-z])/ig,v=/([A-Z])/g,aO=/^-?\d+(?:px)?$/i,aU=/^-?\d/,aK={position:"absolute",visibility:"hidden",display:"block"},W=["Left","Right"],aE=["Top","Bottom"],ak=ab.defaultView&&ab.defaultView.getComputedStyle,aN=a.support.cssFloat?"cssFloat":"styleFloat",k=function(aY,aZ){return aZ.toUpperCase()};a.fn.css=function(aY,aZ){return an(this,aY,aZ,true,function(a1,a0,a2){if(a2===C){return a.curCSS(a1,a0)}if(typeof a2==="number"&&!ar.test(a0)){a2+="px"}a.style(a1,a0,a2)})};a.extend({style:function(a2,aZ,a3){if(!a2||a2.nodeType===3||a2.nodeType===8){return C}if((aZ==="width"||aZ==="height")&&parseFloat(a3)<0){a3=C}var a1=a2.style||a2,a4=a3!==C;if(!a.support.opacity&&aZ==="opacity"){if(a4){a1.zoom=1;var aY=parseInt(a3,10)+""==="NaN"?"":"alpha(opacity="+a3*100+")";var a0=a1.filter||a.curCSS(a2,"filter")||"";a1.filter=U.test(a0)?a0.replace(U,aY):aY}return a1.filter&&a1.filter.indexOf("opacity=")>=0?(parseFloat(aa.exec(a1.filter)[1])/100)+"":""}if(ah.test(aZ)){aZ=aN}aZ=aZ.replace(az,k);if(a4){a1[aZ]=a3}return a1[aZ]},css:function(a1,aZ,a3,aY){if(aZ==="width"||aZ==="height"){var a5,a0=aK,a4=aZ==="width"?W:aE;function a2(){a5=aZ==="width"?a1.offsetWidth:a1.offsetHeight;if(aY==="border"){return}a.each(a4,function(){if(!aY){a5-=parseFloat(a.curCSS(a1,"padding"+this,true))||0}if(aY==="margin"){a5+=parseFloat(a.curCSS(a1,"margin"+this,true))||0}else{a5-=parseFloat(a.curCSS(a1,"border"+this+"Width",true))||0}})}if(a1.offsetWidth!==0){a2()}else{a.swap(a1,a0,a2)}return Math.max(0,Math.round(a5))}return a.curCSS(a1,aZ,a3)},curCSS:function(a4,aZ,a0){var a7,aY=a4.style,a1;if(!a.support.opacity&&aZ==="opacity"&&a4.currentStyle){a7=aa.test(a4.currentStyle.filter||"")?(parseFloat(RegExp.$1)/100)+"":"";return a7===""?"1":a7}if(ah.test(aZ)){aZ=aN}if(!a0&&aY&&aY[aZ]){a7=aY[aZ]}else{if(ak){if(ah.test(aZ)){aZ="float"}aZ=aZ.replace(v,"-$1").toLowerCase();var a6=a4.ownerDocument.defaultView;if(!a6){return null}var a8=a6.getComputedStyle(a4,null);if(a8){a7=a8.getPropertyValue(aZ)}if(aZ==="opacity"&&a7===""){a7="1"}}else{if(a4.currentStyle){var a3=aZ.replace(az,k);a7=a4.currentStyle[aZ]||a4.currentStyle[a3];if(!aO.test(a7)&&aU.test(a7)){var a2=aY.left,a5=a4.runtimeStyle.left;a4.runtimeStyle.left=a4.currentStyle.left;aY.left=a3==="fontSize"?"1em":(a7||0);a7=aY.pixelLeft+"px";aY.left=a2;a4.runtimeStyle.left=a5}}}}return a7},swap:function(a1,a0,a2){var aY={};for(var aZ in a0){aY[aZ]=a1.style[aZ];a1.style[aZ]=a0[aZ]}a2.call(a1);for(var aZ in a0){a1.style[aZ]=aY[aZ]}}});if(a.expr&&a.expr.filters){a.expr.filters.hidden=function(a1){var aZ=a1.offsetWidth,aY=a1.offsetHeight,a0=a1.nodeName.toLowerCase()==="tr";return aZ===0&&aY===0&&!a0?true:aZ>0&&aY>0&&!a0?false:a.curCSS(a1,"display")==="none"};a.expr.filters.visible=function(aY){return !a.expr.filters.hidden(aY)}}var af=aP(),aJ=/<script(.|\s)*?\/script>/gi,o=/select|textarea/i,aB=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,r=/=\?(&|$)/,D=/\?/,aX=/(\?|&)_=.*?(&|$)/,B=/^(\w+:)?\/\/([^\/?#]+)/,h=/%20/g,w=a.fn.load;a.fn.extend({load:function(a0,a3,a4){if(typeof a0!=="string"){return w.call(this,a0)}else{if(!this.length){return this}}var a2=a0.indexOf(" ");if(a2>=0){var aY=a0.slice(a2,a0.length);a0=a0.slice(0,a2)}var a1="GET";if(a3){if(a.isFunction(a3)){a4=a3;a3=null}else{if(typeof a3==="object"){a3=a.param(a3,a.ajaxSettings.traditional);a1="POST"}}}var aZ=this;a.ajax({url:a0,type:a1,dataType:"html",data:a3,complete:function(a6,a5){if(a5==="success"||a5==="notmodified"){aZ.html(aY?a("<div />").append(a6.responseText.replace(aJ,"")).find(aY):a6.responseText)}if(a4){aZ.each(a4,[a6.responseText,a5,a6])}}});return this},serialize:function(){return a.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?a.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||o.test(this.nodeName)||aB.test(this.type))}).map(function(aY,aZ){var a0=a(this).val();return a0==null?null:a.isArray(a0)?a.map(a0,function(a2,a1){return{name:aZ.name,value:a2}}):{name:aZ.name,value:a0}}).get()}});a.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(aY,aZ){a.fn[aZ]=function(a0){return this.bind(aZ,a0)}});a.extend({get:function(aY,a0,a1,aZ){if(a.isFunction(a0)){aZ=aZ||a1;a1=a0;a0=null}return a.ajax({type:"GET",url:aY,data:a0,success:a1,dataType:aZ})},getScript:function(aY,aZ){return a.get(aY,null,aZ,"script")},getJSON:function(aY,aZ,a0){return a.get(aY,aZ,a0,"json")},post:function(aY,a0,a1,aZ){if(a.isFunction(a0)){aZ=aZ||a1;a1=a0;a0={}}return a.ajax({type:"POST",url:aY,data:a0,success:a1,dataType:aZ})},ajaxSetup:function(aY){a.extend(a.ajaxSettings,aY)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:aM.XMLHttpRequest&&(aM.location.protocol!=="file:"||!aM.ActiveXObject)?function(){return new aM.XMLHttpRequest()}:function(){try{return new aM.ActiveXObject("Microsoft.XMLHTTP")}catch(aY){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(bd){var a8=a.extend(true,{},a.ajaxSettings,bd);var bi,bc,bh,bj=bd&&bd.context||a8,a0=a8.type.toUpperCase();if(a8.data&&a8.processData&&typeof a8.data!=="string"){a8.data=a.param(a8.data,a8.traditional)}if(a8.dataType==="jsonp"){if(a0==="GET"){if(!r.test(a8.url)){a8.url+=(D.test(a8.url)?"&":"?")+(a8.jsonp||"callback")+"=?"}}else{if(!a8.data||!r.test(a8.data)){a8.data=(a8.data?a8.data+"&":"")+(a8.jsonp||"callback")+"=?"}}a8.dataType="json"}if(a8.dataType==="json"&&(a8.data&&r.test(a8.data)||r.test(a8.url))){bi=a8.jsonpCallback||("jsonp"+af++);if(a8.data){a8.data=(a8.data+"").replace(r,"="+bi+"$1")}a8.url=a8.url.replace(r,"="+bi+"$1");a8.dataType="script";aM[bi]=aM[bi]||function(bk){bh=bk;a3();a6();aM[bi]=C;try{delete aM[bi]}catch(bl){}if(a1){a1.removeChild(bf)}}}if(a8.dataType==="script"&&a8.cache===null){a8.cache=false}if(a8.cache===false&&a0==="GET"){var aY=aP();var bg=a8.url.replace(aX,"$1_="+aY+"$2");a8.url=bg+((bg===a8.url)?(D.test(a8.url)?"&":"?")+"_="+aY:"")}if(a8.data&&a0==="GET"){a8.url+=(D.test(a8.url)?"&":"?")+a8.data}if(a8.global&&!a.active++){a.event.trigger("ajaxStart")}var bb=B.exec(a8.url),a2=bb&&(bb[1]&&bb[1]!==location.protocol||bb[2]!==location.host);if(a8.dataType==="script"&&a0==="GET"&&a2){var a1=ab.getElementsByTagName("head")[0]||ab.documentElement;var bf=ab.createElement("script");bf.src=a8.url;if(a8.scriptCharset){bf.charset=a8.scriptCharset}if(!bi){var ba=false;bf.onload=bf.onreadystatechange=function(){if(!ba&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){ba=true;a3();a6();bf.onload=bf.onreadystatechange=null;if(a1&&bf.parentNode){a1.removeChild(bf)}}}}a1.insertBefore(bf,a1.firstChild);return C}var a5=false;var a4=a8.xhr();if(!a4){return}if(a8.username){a4.open(a0,a8.url,a8.async,a8.username,a8.password)}else{a4.open(a0,a8.url,a8.async)}try{if(a8.data||bd&&bd.contentType){a4.setRequestHeader("Content-Type",a8.contentType)}if(a8.ifModified){if(a.lastModified[a8.url]){a4.setRequestHeader("If-Modified-Since",a.lastModified[a8.url])}if(a.etag[a8.url]){a4.setRequestHeader("If-None-Match",a.etag[a8.url])}}if(!a2){a4.setRequestHeader("X-Requested-With","XMLHttpRequest")}a4.setRequestHeader("Accept",a8.dataType&&a8.accepts[a8.dataType]?a8.accepts[a8.dataType]+", */*":a8.accepts._default)}catch(be){}if(a8.beforeSend&&a8.beforeSend.call(bj,a4,a8)===false){if(a8.global&&!--a.active){a.event.trigger("ajaxStop")}a4.abort();return false}if(a8.global){a9("ajaxSend",[a4,a8])}var a7=a4.onreadystatechange=function(bk){if(!a4||a4.readyState===0||bk==="abort"){if(!a5){a6()}a5=true;if(a4){a4.onreadystatechange=a.noop}}else{if(!a5&&a4&&(a4.readyState===4||bk==="timeout")){a5=true;a4.onreadystatechange=a.noop;bc=bk==="timeout"?"timeout":!a.httpSuccess(a4)?"error":a8.ifModified&&a.httpNotModified(a4,a8.url)?"notmodified":"success";var bm;if(bc==="success"){try{bh=a.httpData(a4,a8.dataType,a8)}catch(bl){bc="parsererror";bm=bl}}if(bc==="success"||bc==="notmodified"){if(!bi){a3()}}else{a.handleError(a8,a4,bc,bm)}a6();if(bk==="timeout"){a4.abort()}if(a8.async){a4=null}}}};try{var aZ=a4.abort;a4.abort=function(){if(a4){aZ.call(a4)}a7("abort")}}catch(be){}if(a8.async&&a8.timeout>0){setTimeout(function(){if(a4&&!a5){a7("timeout")}},a8.timeout)}try{a4.send(a0==="POST"||a0==="PUT"||a0==="DELETE"?a8.data:null)}catch(be){a.handleError(a8,a4,null,be);a6()}if(!a8.async){a7()}function a3(){if(a8.success){a8.success.call(bj,bh,bc,a4)}if(a8.global){a9("ajaxSuccess",[a4,a8])}}function a6(){if(a8.complete){a8.complete.call(bj,a4,bc)}if(a8.global){a9("ajaxComplete",[a4,a8])}if(a8.global&&!--a.active){a.event.trigger("ajaxStop")}}function a9(bl,bk){(a8.context?a(a8.context):a.event).trigger(bl,bk)}return a4},handleError:function(aZ,a1,aY,a0){if(aZ.error){aZ.error.call(aZ.context||aZ,a1,aY,a0)}if(aZ.global){(aZ.context?a(aZ.context):a.event).trigger("ajaxError",[a1,aZ,a0])}},active:0,httpSuccess:function(aZ){try{return !aZ.status&&location.protocol==="file:"||(aZ.status>=200&&aZ.status<300)||aZ.status===304||aZ.status===1223||aZ.status===0}catch(aY){}return false},httpNotModified:function(a1,aY){var a0=a1.getResponseHeader("Last-Modified"),aZ=a1.getResponseHeader("Etag");if(a0){a.lastModified[aY]=a0}if(aZ){a.etag[aY]=aZ}return a1.status===304||a1.status===0},httpData:function(a3,a1,a0){var aZ=a3.getResponseHeader("content-type")||"",aY=a1==="xml"||!a1&&aZ.indexOf("xml")>=0,a2=aY?a3.responseXML:a3.responseText;if(aY&&a2.documentElement.nodeName==="parsererror"){a.error("parsererror")}if(a0&&a0.dataFilter){a2=a0.dataFilter(a2,a1)}if(typeof a2==="string"){if(a1==="json"||!a1&&aZ.indexOf("json")>=0){a2=a.parseJSON(a2)}else{if(a1==="script"||!a1&&aZ.indexOf("javascript")>=0){a.globalEval(a2)}}}return a2},param:function(aY,a1){var aZ=[];if(a1===C){a1=a.ajaxSettings.traditional}if(a.isArray(aY)||aY.jquery){a.each(aY,function(){a3(this.name,this.value)})}else{for(var a2 in aY){a0(a2,aY[a2])}}return aZ.join("&").replace(h,"+");function a0(a4,a5){if(a.isArray(a5)){a.each(a5,function(a7,a6){if(a1||/\[\]$/.test(a4)){a3(a4,a6)}else{a0(a4+"["+(typeof a6==="object"||a.isArray(a6)?a7:"")+"]",a6)}})}else{if(!a1&&a5!=null&&typeof a5==="object"){a.each(a5,function(a7,a6){a0(a4+"["+a7+"]",a6)})}else{a3(a4,a5)}}}function a3(a4,a5){a5=a.isFunction(a5)?a5():a5;aZ[aZ.length]=encodeURIComponent(a4)+"="+encodeURIComponent(a5)}}});var G={},ae=/toggle|show|hide/,au=/^([+-]=)?([\d+-.]+)(.*)$/,aF,aj=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];a.fn.extend({show:function(aZ,a7){if(aZ||aZ===0){return this.animate(aD("show",3),aZ,a7)}else{for(var a4=0,a1=this.length;a4<a1;a4++){var aY=a.data(this[a4],"olddisplay");this[a4].style.display=aY||"";if(a.css(this[a4],"display")==="none"){var a6=this[a4].nodeName,a5;if(G[a6]){a5=G[a6]}else{var a0=a("<"+a6+" />").appendTo("body");a5=a0.css("display");if(a5==="none"){a5="block"}a0.remove();G[a6]=a5}a.data(this[a4],"olddisplay",a5)}}for(var a3=0,a2=this.length;a3<a2;a3++){this[a3].style.display=a.data(this[a3],"olddisplay")||""}return this}},hide:function(a3,a4){if(a3||a3===0){return this.animate(aD("hide",3),a3,a4)}else{for(var a2=0,aZ=this.length;a2<aZ;a2++){var aY=a.data(this[a2],"olddisplay");if(!aY&&aY!=="none"){a.data(this[a2],"olddisplay",a.css(this[a2],"display"))}}for(var a1=0,a0=this.length;a1<a0;a1++){this[a1].style.display="none"}return this}},_toggle:a.fn.toggle,toggle:function(a0,aZ){var aY=typeof a0==="boolean";if(a.isFunction(a0)&&a.isFunction(aZ)){this._toggle.apply(this,arguments)}else{if(a0==null||aY){this.each(function(){var a1=aY?a0:a(this).is(":hidden");a(this)[a1?"show":"hide"]()})}else{this.animate(aD("toggle",3),a0,aZ)}}return this},fadeTo:function(aY,a0,aZ){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:a0},aY,aZ)},animate:function(a2,aZ,a1,a0){var aY=a.speed(aZ,a1,a0);if(a.isEmptyObject(a2)){return this.each(aY.complete)}return this[aY.queue===false?"each":"queue"](function(){var a5=a.extend({},aY),a7,a6=this.nodeType===1&&a(this).is(":hidden"),a3=this;for(a7 in a2){var a4=a7.replace(az,k);if(a7!==a4){a2[a4]=a2[a7];delete a2[a7];a7=a4}if(a2[a7]==="hide"&&a6||a2[a7]==="show"&&!a6){return a5.complete.call(this)}if((a7==="height"||a7==="width")&&this.style){a5.display=a.css(this,"display");a5.overflow=this.style.overflow}if(a.isArray(a2[a7])){(a5.specialEasing=a5.specialEasing||{})[a7]=a2[a7][1];a2[a7]=a2[a7][0]}}if(a5.overflow!=null){this.style.overflow="hidden"}a5.curAnim=a.extend({},a2);a.each(a2,function(a9,bd){var bc=new a.fx(a3,a5,a9);if(ae.test(bd)){bc[bd==="toggle"?a6?"show":"hide":bd](a2)}else{var bb=au.exec(bd),be=bc.cur(true)||0;if(bb){var a8=parseFloat(bb[2]),ba=bb[3]||"px";if(ba!=="px"){a3.style[a9]=(a8||1)+ba;be=((a8||1)/bc.cur(true))*be;a3.style[a9]=be+ba}if(bb[1]){a8=((bb[1]==="-="?-1:1)*a8)+be}bc.custom(be,a8,ba)}else{bc.custom(be,bd,"")}}});return true})},stop:function(aZ,aY){var a0=a.timers;if(aZ){this.queue([])}this.each(function(){for(var a1=a0.length-1;a1>=0;a1--){if(a0[a1].elem===this){if(aY){a0[a1](true)}a0.splice(a1,1)}}});if(!aY){this.dequeue()}return this}});a.each({slideDown:aD("show",1),slideUp:aD("hide",1),slideToggle:aD("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(aY,aZ){a.fn[aY]=function(a0,a1){return this.animate(aZ,a0,a1)}});a.extend({speed:function(a0,a1,aZ){var aY=a0&&typeof a0==="object"?a0:{complete:aZ||!aZ&&a1||a.isFunction(a0)&&a0,duration:a0,easing:aZ&&a1||a1&&!a.isFunction(a1)&&a1};aY.duration=a.fx.off?0:typeof aY.duration==="number"?aY.duration:a.fx.speeds[aY.duration]||a.fx.speeds._default;aY.old=aY.complete;aY.complete=function(){if(aY.queue!==false){a(this).dequeue()}if(a.isFunction(aY.old)){aY.old.call(this)}};return aY},easing:{linear:function(a0,a1,aY,aZ){return aY+aZ*a0},swing:function(a0,a1,aY,aZ){return((-Math.cos(a0*Math.PI)/2)+0.5)*aZ+aY}},timers:[],fx:function(aZ,aY,a0){this.options=aY;this.elem=aZ;this.prop=a0;if(!aY.orig){aY.orig={}}}});a.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(a.fx.step[this.prop]||a.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(aZ){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var aY=parseFloat(a.css(this.elem,this.prop,aZ));return aY&&aY>-10000?aY:parseFloat(a.curCSS(this.elem,this.prop))||0},custom:function(a2,a1,a0){this.startTime=aP();this.start=a2;this.end=a1;this.unit=a0||this.unit||"px";this.now=this.start;this.pos=this.state=0;var aY=this;function aZ(a3){return aY.step(a3)}aZ.elem=this.elem;if(aZ()&&a.timers.push(aZ)&&!aF){aF=setInterval(a.fx.tick,13)}},show:function(){this.options.orig[this.prop]=a.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());a(this.elem).show()},hide:function(){this.options.orig[this.prop]=a.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a1){var a6=aP(),a2=true;if(a1||a6>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var a3 in this.options.curAnim){if(this.options.curAnim[a3]!==true){a2=false}}if(a2){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;var a0=a.data(this.elem,"olddisplay");this.elem.style.display=a0?a0:this.options.display;if(a.css(this.elem,"display")==="none"){this.elem.style.display="block"}}if(this.options.hide){a(this.elem).hide()}if(this.options.hide||this.options.show){for(var aY in this.options.curAnim){a.style(this.elem,aY,this.options.orig[aY])}}this.options.complete.call(this.elem)}return false}else{var aZ=a6-this.startTime;this.state=aZ/this.options.duration;var a4=this.options.specialEasing&&this.options.specialEasing[this.prop];var a5=this.options.easing||(a.easing.swing?"swing":"linear");this.pos=a.easing[a4||a5](this.state,aZ,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};a.extend(a.fx,{tick:function(){var aZ=a.timers;for(var aY=0;aY<aZ.length;aY++){if(!aZ[aY]()){aZ.splice(aY--,1)}}if(!aZ.length){a.fx.stop()}},stop:function(){clearInterval(aF);aF=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(aY){a.style(aY.elem,"opacity",aY.now)},_default:function(aY){if(aY.elem.style&&aY.elem.style[aY.prop]!=null){aY.elem.style[aY.prop]=(aY.prop==="width"||aY.prop==="height"?Math.max(0,aY.now):aY.now)+aY.unit}else{aY.elem[aY.prop]=aY.now}}}});if(a.expr&&a.expr.filters){a.expr.filters.animated=function(aY){return a.grep(a.timers,function(aZ){return aY===aZ.elem}).length}}function aD(aZ,aY){var a0={};a.each(aj.concat.apply([],aj.slice(0,aY)),function(){a0[this]=aZ});return a0}if("getBoundingClientRect" in ab.documentElement){a.fn.offset=function(a7){var a0=this[0];if(a7){return this.each(function(a8){a.offset.setOffset(this,a7,a8)})}if(!a0||!a0.ownerDocument){return null}if(a0===a0.ownerDocument.body){return a.offset.bodyOffset(a0)}var a2=a0.getBoundingClientRect(),a6=a0.ownerDocument,a3=a6.body,aY=a6.documentElement,a1=aY.clientTop||a3.clientTop||0,a4=aY.clientLeft||a3.clientLeft||0,a5=a2.top+(self.pageYOffset||a.support.boxModel&&aY.scrollTop||a3.scrollTop)-a1,aZ=a2.left+(self.pageXOffset||a.support.boxModel&&aY.scrollLeft||a3.scrollLeft)-a4;return{top:a5,left:aZ}}}else{a.fn.offset=function(a9){var a3=this[0];if(a9){return this.each(function(ba){a.offset.setOffset(this,a9,ba)})}if(!a3||!a3.ownerDocument){return null}if(a3===a3.ownerDocument.body){return a.offset.bodyOffset(a3)}a.offset.initialize();var a0=a3.offsetParent,aZ=a3,a8=a3.ownerDocument,a6,a1=a8.documentElement,a4=a8.body,a5=a8.defaultView,aY=a5?a5.getComputedStyle(a3,null):a3.currentStyle,a7=a3.offsetTop,a2=a3.offsetLeft;while((a3=a3.parentNode)&&a3!==a4&&a3!==a1){if(a.offset.supportsFixedPosition&&aY.position==="fixed"){break}a6=a5?a5.getComputedStyle(a3,null):a3.currentStyle;a7-=a3.scrollTop;a2-=a3.scrollLeft;if(a3===a0){a7+=a3.offsetTop;a2+=a3.offsetLeft;if(a.offset.doesNotAddBorder&&!(a.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(a3.nodeName))){a7+=parseFloat(a6.borderTopWidth)||0;a2+=parseFloat(a6.borderLeftWidth)||0}aZ=a0,a0=a3.offsetParent}if(a.offset.subtractsBorderForOverflowNotVisible&&a6.overflow!=="visible"){a7+=parseFloat(a6.borderTopWidth)||0;a2+=parseFloat(a6.borderLeftWidth)||0}aY=a6}if(aY.position==="relative"||aY.position==="static"){a7+=a4.offsetTop;a2+=a4.offsetLeft}if(a.offset.supportsFixedPosition&&aY.position==="fixed"){a7+=Math.max(a1.scrollTop,a4.scrollTop);a2+=Math.max(a1.scrollLeft,a4.scrollLeft)}return{top:a7,left:a2}}}a.offset={initialize:function(){var aY=ab.body,aZ=ab.createElement("div"),a2,a4,a3,a5,a0=parseFloat(a.curCSS(aY,"marginTop",true))||0,a1="<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>";a.extend(aZ.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});aZ.innerHTML=a1;aY.insertBefore(aZ,aY.firstChild);a2=aZ.firstChild;a4=a2.firstChild;a5=a2.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(a4.offsetTop!==5);this.doesAddBorderForTableAndCells=(a5.offsetTop===5);a4.style.position="fixed",a4.style.top="20px";this.supportsFixedPosition=(a4.offsetTop===20||a4.offsetTop===15);a4.style.position=a4.style.top="";a2.style.overflow="hidden",a2.style.position="relative";this.subtractsBorderForOverflowNotVisible=(a4.offsetTop===-5);this.doesNotIncludeMarginInBodyOffset=(aY.offsetTop!==a0);aY.removeChild(aZ);aY=aZ=a2=a4=a3=a5=null;a.offset.initialize=a.noop},bodyOffset:function(aY){var a0=aY.offsetTop,aZ=aY.offsetLeft;a.offset.initialize();if(a.offset.doesNotIncludeMarginInBodyOffset){a0+=parseFloat(a.curCSS(aY,"marginTop",true))||0;aZ+=parseFloat(a.curCSS(aY,"marginLeft",true))||0}return{top:a0,left:aZ}},setOffset:function(a3,aZ,a0){if(/static/.test(a.curCSS(a3,"position"))){a3.style.position="relative"}var a2=a(a3),a5=a2.offset(),aY=parseInt(a.curCSS(a3,"top",true),10)||0,a4=parseInt(a.curCSS(a3,"left",true),10)||0;if(a.isFunction(aZ)){aZ=aZ.call(a3,a0,a5)}var a1={top:(aZ.top-a5.top)+aY,left:(aZ.left-a5.left)+a4};if("using" in aZ){aZ.using.call(a3,a1)}else{a2.css(a1)}}};a.fn.extend({position:function(){if(!this[0]){return null}var a0=this[0],aZ=this.offsetParent(),a1=this.offset(),aY=/^body|html$/i.test(aZ[0].nodeName)?{top:0,left:0}:aZ.offset();a1.top-=parseFloat(a.curCSS(a0,"marginTop",true))||0;a1.left-=parseFloat(a.curCSS(a0,"marginLeft",true))||0;aY.top+=parseFloat(a.curCSS(aZ[0],"borderTopWidth",true))||0;aY.left+=parseFloat(a.curCSS(aZ[0],"borderLeftWidth",true))||0;return{top:a1.top-aY.top,left:a1.left-aY.left}},offsetParent:function(){return this.map(function(){var aY=this.offsetParent||ab.body;while(aY&&(!/^body|html$/i.test(aY.nodeName)&&a.css(aY,"position")==="static")){aY=aY.offsetParent}return aY})}});a.each(["Left","Top"],function(aZ,aY){var a0="scroll"+aY;a.fn[a0]=function(a3){var a1=this[0],a2;if(!a1){return null}if(a3!==C){return this.each(function(){a2=am(this);if(a2){a2.scrollTo(!aZ?a3:a(a2).scrollLeft(),aZ?a3:a(a2).scrollTop())}else{this[a0]=a3}})}else{a2=am(a1);return a2?("pageXOffset" in a2)?a2[aZ?"pageYOffset":"pageXOffset"]:a.support.boxModel&&a2.document.documentElement[a0]||a2.document.body[a0]:a1[a0]}}});function am(aY){return("scrollTo" in aY&&aY.document)?aY:aY.nodeType===9?aY.defaultView||aY.parentWindow:false}a.each(["Height","Width"],function(aZ,aY){var a0=aY.toLowerCase();a.fn["inner"+aY]=function(){return this[0]?a.css(this[0],a0,false,"padding"):null};a.fn["outer"+aY]=function(a1){return this[0]?a.css(this[0],a0,false,a1?"margin":"border"):null};a.fn[a0]=function(a1){var a2=this[0];if(!a2){return a1==null?null:this}if(a.isFunction(a1)){return this.each(function(a4){var a3=a(this);a3[a0](a1.call(this,a4,a3[a0]()))})}return("scrollTo" in a2&&a2.document)?a2.document.compatMode==="CSS1Compat"&&a2.document.documentElement["client"+aY]||a2.document.body["client"+aY]:(a2.nodeType===9)?Math.max(a2.documentElement["client"+aY],a2.body["scroll"+aY],a2.documentElement["scroll"+aY],a2.body["offset"+aY],a2.documentElement["offset"+aY]):a1===C?a.css(a2,a0):this.css(a0,typeof a1==="string"?a1:a1+"px")}});aM.jQuery=aM.$=a})(window);(function(bU,r,bi){var b8=bU.jQuery.noConflict(true);if(typeof r.getAttribute==q){r.getAttribute=function(){}}var am=function(cV){return ci(cV)?cV.toLowerCase():cV};var bI=function(cV){return ci(cV)?cV.toUpperCase():cV};var aE=function(cV){return ci(cV)?cV.replace(/[A-Z]/g,function(cW){return G(cW.charCodeAt(0)|32)}):cV};var ce=function(cV){return ci(cV)?cV.replace(/[a-z]/g,function(cW){return G(cW.charCodeAt(0)&~32)}):cV};if("i"!=="I".toLowerCase()){am=aE;bI=ce}function G(cV){return String.fromCharCode(cV)}var cS=undefined,a6=null,by="$element",ac="$update",bR="$scope",bf="$validate",R="angular",a3="array",b9="boolean",bA="console",bc="date",aL="display",cC="element",bz="function",ai="length",Y="name",b="none",cE="noop",v="null",ch="number",aP="object",P="string",ay="value",aA="selected",q="undefined",a="ng-exception",k="ng-validation-error",o="noop",bp=-99999,an=-1000,cg=99999,aM={FIRST:bp,LAST:cg,WATCH:an},cK=bU.Error,cx=bU.jQuery||bU["$"],ca=bU._,at=parseInt((/msie (\d+)/.exec(am(navigator.userAgent))||[])[1],10),ck=cx||cL,ad=Array.prototype.slice,C=Array.prototype.push,cG=bU[bA]?bF(bU[bA],bU[bA]["error"]||j):j,aB=bU[R]||(bU[R]={}),ag=bo(aB,"markup"),s=bo(aB,"attrMarkup"),Z=bo(aB,"directive"),B=bo(aB,"widget",am),aK=bo(aB,"validator"),cu=bo(aB,"filter"),l=bo(aB,"formatter"),bs=bo(aB,"service"),bg=bo(aB,"callbacks"),au,ab=/^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/;function aS(cY,cX,cW){var cV;if(cY){if(E(cY)){for(cV in cY){if(cV!="prototype"&&cV!=ai&&cV!=Y&&cY.hasOwnProperty(cV)){cX.call(cW,cY[cV],cV)}}}else{if(cY.forEach){cY.forEach(cX,cW)}else{if(cR(cY)&&aU(cY.length)){for(cV=0;cV<cY.length;cV++){cX.call(cW,cY[cV],cV)}}else{for(cV in cY){cX.call(cW,cY[cV],cV)}}}}}return cY}function ar(c0,cY,cX){var cZ=[];for(var cW in c0){cZ.push(cW)}cZ.sort();for(var cV=0;cV<cZ.length;cV++){cY.call(cX,c0[cZ[cV]],cZ[cV])}return cZ}function bb(cV){if(cV instanceof cK){if(cV.stack){cV=cV.stack}else{if(cV.sourceURL){cV=cV.message+"\n"+cV.sourceURL+":"+cV.line}}}return cV}function b7(cV){aS(arguments,function(cW){if(cW!==cV){aS(cW,function(cY,cX){cV[cX]=cY})}});return cV}function b5(cW,cV){return b7(new (b7(function(){},{prototype:cW}))(),cV)}function j(){}function aG(cV){return cV}function cr(cV){return function(){return cV}}function bo(cX,cW,cV){var cY;return cX[cW]||(cY=cX[cW]=function(cZ,c0,c1){cZ=(cV||aG)(cZ);if(cv(c0)){if(cv(cY[cZ])){aS(cY[cZ],function(c3,c2){if(c2.charAt(0)=="$"&&bB(c0[c2])){c0[c2]=c3}})}cY[cZ]=b7(c0,c1||{})}return cY[cZ]})}function cL(cV){if(cV){if(ci(cV)){var cW=r.createElement("div");cW.innerHTML=cV;cV=new bu(cW.childNodes)}else{if(!(cV instanceof bu)&&bJ(cV)){cV=new bu(cV)}}}return cV}function bB(cV){return typeof cV==q}function cv(cV){return typeof cV!=q}function cR(cV){return cV!=a6&&typeof cV==aP}function ci(cV){return typeof cV==P}function aU(cV){return typeof cV==ch}function ax(cV){return cV instanceof Date}function a9(cV){return cV instanceof Array}function E(cV){return typeof cV==bz}function be(cV){return typeof cV==b9}function t(cV){return au(cV)=="#text"}function av(cV){return ci(cV)?cV.replace(/^\s*/,"").replace(/\s*$/,""):cV}function bJ(cV){return cV&&(cV.nodeName||cV instanceof bu||(cx&&cV instanceof cx))}function aW(cW,cX){this.html=cW;this.get=am(cX)=="unsafe"?cr(cW):function cV(){var cY=[];aQ(cW,a5(cY));return cY.join("")}}if(at){au=function(cV){cV=cV.nodeName?cV:cV[0];return(cV.scopeName&&cV.scopeName!="HTML")?bI(cV.scopeName+":"+cV.nodeName):cV.nodeName}}else{au=function(cV){return cV.nodeName?cV.nodeName:cV[0].nodeName}}function A(cV){return ck(cV[0].cloneNode(true))}function aR(cW){var cY=cW[0].getBoundingClientRect(),cX=(cY.width||(cY.right||0-cY.left||0)),cV=(cY.height||(cY.bottom||0-cY.top||0));return cX>0&&cV>0}function aI(cY,cX,cW){var cV=[];aS(cY,function(c1,cZ,c0){cV.push(cX.call(cW,c1,cZ,c0))});return cV}function aw(cW){var cV=0;if(cW){if(aU(cW.length)){return cW.length}else{if(cR(cW)){for(key in cW){cV++}}}}return cV}function u(cX,cW){for(var cV=0;cV<cX.length;cV++){if(cW===cX[cV]){return true}}return false}function cO(cX,cW){for(var cV=0;cV<cX.length;cV++){if(cW===cX[cV]){return cV}}return -1}function b4(cV){if(cV){switch(cV.nodeName){case"OPTION":case"PRE":case"TITLE":return true}}return false}function bv(cY,cV){if(!cV){cV=cY;if(cY){if(a9(cY)){cV=bv(cY,[])}else{if(ax(cY)){cV=new Date(cY.getTime())}else{if(cR(cY)){cV=bv(cY,{})}}}}}else{if(a9(cY)){while(cV.length){cV.pop()}for(var cX=0;cX<cY.length;cX++){cV.push(bv(cY[cX]))}}else{aS(cV,function(c0,cZ){delete cV[cZ]});for(var cW in cY){cV[cW]=bv(cY[cW])}}}return cV}function p(c1,c0){if(c1==c0){return true}var cZ=typeof c1,cX=typeof c0,cY,cW,cV;if(cZ==cX&&cZ=="object"){if(c1 instanceof Array){if((cY=c1.length)==c0.length){for(cW=0;cW<cY;cW++){if(!p(c1[cW],c0[cW])){return false}}return true}}else{cV={};for(cW in c1){if(cW.charAt(0)!=="$"&&!E(c1[cW])&&!p(c1[cW],c0[cW])){return false}cV[cW]=true}for(cW in c0){if(!cV[cW]&&cW.charAt(0)!=="$"&&!E(c0[cW])){return false}}return true}}return false}function U(cW,cV){if(b4(cW)){if(at){cW.innerText=cV}else{cW.textContent=cV}}else{cW.innerHTML=cV}}function bM(cW){var cV=cW&&cW[0]&&cW[0].nodeName;return cV&&cV.charAt(0)!="#"&&!u(["TR","COL","COLGROUP","TBODY","THEAD","TFOOT"],cV)}function b0(cW,cX,cV){while(!bM(cW)){cW=cW.parent()||ck(r.body)}if(cW[0]["$NG_ERROR"]!==cV){cW[0]["$NG_ERROR"]=cV;if(cV){cW.addClass(cX);cW.attr(cX,cV)}else{cW.removeClass(cX);cW.removeAttr(cX)}}}function bd(cX,cW,cV){return cX.concat(ad.call(cW,cV,cW.length))}function bF(cW,cX){var cV=arguments.length>2?ad.call(arguments,2,arguments.length):[];if(typeof cX==bz){return cV.length?function(){return arguments.length?cX.apply(cW,cV.concat(ad.call(arguments,0,arguments.length))):cX.apply(cW,cV)}:function(){return arguments.length?cX.apply(cW,arguments):cX.call(cW)}}else{return cX}}function cp(cW){if(cW&&cW.length!==0){var cV=am(""+cW);cW=!(cV=="f"||cV=="0"||cV=="false"||cV=="no"||cV=="n"||cV=="[]")}else{cW=false}return cW}function bm(cY,cZ){for(var cV in cY){var cX=cZ[cV];var cW=typeof cX;if(cW==q){cZ[cV]=Q(cm(cY[cV]))}else{if(cW=="object"&&cX.constructor!=F&&cV.substring(0,1)!="$"){bm(cY[cV],cX)}}}}function a2(cW,cY){var cX=new ba(ag,s,Z,B),cV=ck(cW);return cX.compile(cV)(cV,cY)}function ah(cY){var cX={},cV,cW;aS((cY||"").split("&"),function(cZ){if(cZ){cV=cZ.split("=");cW=unescape(cV[0]);cX[cW]=cv(cV[1])?unescape(cV[1]):true}});return cX}function N(cW){var cV=[];aS(cW,function(cY,cX){cV.push(escape(cX)+(cY===true?"":"="+escape(cY)))});return cV.length?cV.join("&"):""}function bw(cW){if(cW.autobind){var cX=a2(bU.document,a6,{"$config":cW}),cV=cX.$inject("$browser");if(cW.css){cV.addCss(cW.base_url+cW.css)}else{if(at<8){cV.addJs(cW.base_url+cW.ie_compat,cW.ie_compat_id)}}cX.$init()}}function bH(cW,cZ){var cV=cW.getElementsByTagName("script"),cY;cZ=b7({ie_compat_id:"ng-ie-compat"},cZ);for(var cX=0;cX<cV.length;cX++){cY=(cV[cX].src||"").match(ab);if(cY){cZ.base_url=cY[1];cZ.ie_compat=cY[1]+"angular-ie-compat"+(cY[2]||"")+".js";b7(cZ,ah(cY[6]));a4(ck(cV[cX]),function(c1,c0){if(/^ng:/.exec(c0)){c0=c0.substring(3).replace(/-/g,"_");if(c0=="autobind"){c1=true}cZ[c0]=c1}})}}return cZ}var F=[].constructor;function cm(cX,cW){var cV=[];bS(cV,cX,cW?"\n ":a6,[]);return cV.join("")}function Q(cV){if(!cV){return cV}try{var cX=S(cV,true);var cY=cX.primary();cX.assertAllConsumed();return cY()}catch(cW){cG("fromJson error: ",cV,cW);throw cW}}aB.toJson=cm;aB.fromJson=Q;function bS(cW,cY,c1,c2){if(cR(cY)){if(cY===bU){cW.push("WINDOW");return}if(cY===r){cW.push("DOCUMENT");return}if(u(c2,cY)){cW.push("RECURSION");return}c2.push(cY)}if(cY===a6){cW.push(v)}else{if(cY instanceof RegExp){cW.push(aB.String["quoteUnicode"](cY.toString()))}else{if(E(cY)){return}else{if(be(cY)){cW.push(""+cY)}else{if(aU(cY)){if(isNaN(cY)){cW.push(v)}else{cW.push(""+cY)}}else{if(ci(cY)){return cW.push(aB.String["quoteUnicode"](cY))}else{if(cR(cY)){if(a9(cY)){cW.push("[");var c0=cY.length;var c9=false;for(var cZ=0;cZ<c0;cZ++){var c6=cY[cZ];if(c9){cW.push(",")}if(!(c6 instanceof RegExp)&&(E(c6)||bB(c6))){cW.push(v)}else{bS(cW,c6,c1,c2)}c9=true}cW.push("]")}else{if(ax(cY)){cW.push(aB.String["quoteUnicode"](aB.Date["toString"](cY)))}else{cW.push("{");if(c1){cW.push(c1)}var c8=false;var c7=c1?c1+" ":false;var c5=[];for(var cX in cY){if(cY[cX]===cS){continue}c5.push(cX)}c5.sort();for(var cV=0;cV<c5.length;cV++){var c4=c5[cV];var c3=cY[c4];if(typeof c3!=bz){if(c8){cW.push(",");if(c1){cW.push(c1)}}cW.push(aB.String["quote"](c4));cW.push(":");bS(cW,c3,c7,c2);c8=true}}cW.push("}")}}}}}}}}}if(cR(cY)){c2.pop()}}function cw(cV){this.paths=[];this.children=[];this.inits=[];this.priority=cV;this.newScope=false}cw.prototype={init:function(cV,cW){var cX={};this.collectInits(cV,cX,cW);ar(cX,function(cY){aS(cY,function(cZ){cZ()})})},collectInits:function(cX,c0,c3){var cZ=c0[this.priority],c1=c3;if(!cZ){c0[this.priority]=cZ=[]}cX=ck(cX);if(this.newScope){c1=bV(c3);c3.$onEval(c1.$eval);cX.data(bR,c1)}aS(this.inits,function(c5){cZ.push(function(){c1.$tryEval(function(){return c1.$inject(c5,c1,cX)},cX)})});var cY,c2=cX[0].childNodes,cW=this.children,c4=this.paths,cV=c4.length;for(cY=0;cY<cV;cY++){cW[cY].collectInits(c2[c4[cY]],c0,c1)}},addInit:function(cV){if(cV){this.inits.push(cV)}},addChild:function(cV,cW){if(cW){this.paths.push(cV);this.children.push(cW)}},empty:function(){return this.inits.length===0&&this.paths.length===0}};function ae(cV){var cW;while(cV&&!(cW=cV.data(bR))){cV=cV.parent()}return cW}function ba(cV,cW,cY,cX){this.markup=cV;this.attrMarkup=cW;this.directives=cY;this.widgets=cX}ba.prototype={compile:function(cZ){cZ=ck(cZ);var cV=0,cY,cX=cZ.parent();if(cX&&cX[0]){cX=cX[0];for(var cW=0;cW<cX.childNodes.length;cW++){if(cX.childNodes[cW]==cZ[0]){cV=cW}}}cY=this.templatize(cZ,cV,0)||new cw();return function(c0,c2){c0=ck(c0);var c1=c2&&c2.$eval?c2:bV(c2);c0.data(bR,c1);return b7(c1,{$element:c0,$init:function(){cY.init(c0,c1);c1.$eval();delete c1.$init;return c1}})}},templatize:function(c0,cW,c5){var c9=this,c1,c4,cX=c9.directives,c3=true,cY=true,da=au(c0),c8,c7={compile:bF(c9,c9.compile),comment:function(db){return ck(r.createComment(db))},element:function(db){return ck(r.createElement(db))},text:function(db){return ck(r.createTextNode(db))},descend:function(db){if(cv(db)){c3=db}return c3},directives:function(db){if(cv(db)){cY=db}return cY},scope:function(db){if(cv(db)){c8.newScope=c8.newScope||db}return c8.newScope}};try{c5=c0.attr("ng:eval-order")||c5||0}catch(c2){c5=c5||0}if(ci(c5)){c5=aM[bI(c5)]||parseInt(c5,10)}c8=new cw(c5);a4(c0,function(dc,db){if(!c1){if(c1=c9.widgets("@"+db)){c0.addClass("ng-attr-widget");c1=bF(c7,c1,dc,c0)}}});if(!c1){if(c1=c9.widgets(da)){if(da.indexOf(":")>0){c0.addClass("ng-widget")}c1=bF(c7,c1,c0)}}if(c1){c3=false;cY=false;var c6=c0.parent();c8.addInit(c1.call(c7,c0));if(c6&&c6[0]){c0=ck(c6[0].childNodes[cW])}}if(c3){for(var cZ=0,cV=c0[0].childNodes;cZ<cV.length;cZ++){if(t(cV[cZ])){aS(c9.markup,function(db){if(cZ<cV.length){var dc=ck(cV[cZ]);db.call(c7,dc.text(),dc,c0)}})}}}if(cY){a4(c0,function(dc,db){aS(c9.attrMarkup,function(dd){dd.call(c7,dc,db,c0)})});a4(c0,function(dc,db){c4=cX[db];if(c4){c0.addClass("ng-directive");c8.addInit((cX[db]).call(c7,dc,c0))}})}if(c3){aX(c0,function(dc,db){c8.addChild(db,c9.templatize(dc,db,c5))})}return c8.empty()?a6:c8}};function aX(cW,cX){var cV,cZ=cW[0].childNodes||[],cY;for(cV=0;cV<cZ.length;cV++){if(!t(cY=cZ[cV])){cX(ck(cY),cV)}}}function a4(cW,c0){var cX,c3=cW[0].attributes||[],c2,cZ,cV,c1,cY={};for(cX=0;cX<c3.length;cX++){cZ=c3[cX];cV=cZ.name;c1=cZ.value;if(at&&cV=="href"){c1=decodeURIComponent(cW[0].getAttribute(cV,2))}cY[cV]=c1}ar(cY,c0)}function bQ(c3,c4,c1){if(!c4){return c3}var cW=c4.split(".");var c2;var cV=c3;var cY=cW.length;for(var cX=0;cX<cY;cX++){c2=cW[cX];if(!c2.match(/^[\$\w][\$\w\d]*$/)){throw"Expression '"+c4+"' is not a valid expression for accesing variables."}if(c3){cV=c3;c3=c3[c2]}if(bB(c3)&&c2.charAt(0)=="$"){var cZ=aB.Global["typeOf"](cV);cZ=aB[cZ.charAt(0).toUpperCase()+cZ.substring(1)];var c0=cZ?cZ[[c2.substring(1)]]:cS;if(c0){c3=bF(cV,c0,cV);return c3}}}if(!c1&&E(c3)){return bF(cV,c3)}return c3}function cd(cV,c1,c0){var cZ=c1.split(".");for(var cY=0;cZ.length>1;cY++){var cX=cZ.shift();var cW=cV[cX];if(!cW){cW={};cV[cX]=cW}cV=cW}cV[cZ.shift()]=c0;return c0}var az=0,cD={},aN={},cN={};aS(("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default,delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto,if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private,protected,public,return,short,static,super,switch,synchronized,this,throw,throws,transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/),function(cV){cN[cV]=true});function co(cX){var cV=cD[cX];if(cV){return cV}var cW="var l, fn, t;\n";aS(cX.split("."),function(cZ){cZ=(cN[cZ])?'["'+cZ+'"]':"."+cZ;cW+="if(!s) return s;\nl=s;\ns=s"+cZ+';\nif(typeof s=="function" && !(s instanceof RegExp)) s = function(){ return l'+cZ+".apply(l, arguments); };\n";if(cZ.charAt(1)=="$"){var cY=cZ.substr(2);cW+='if(!s) {\n t = angular.Global.typeOf(l);\n fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["'+cY+'"];\n if (fn) s = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0, arguments.length))); };\n}\n'}});cW+="return s;";cV=Function("s",cW);cV.toString=function(){return cW};return cD[cX]=cV}function bt(cY){if(typeof cY===bz){return cY}var cV=aN[cY];if(!cV){var cW=S(cY);var cX=cW.statements();cW.assertAllConsumed();cV=aN[cY]=b7(function(){return cX(this)},{fnSelf:cX})}return cV}function ao(cW,cV){b0(cW,a,cv(cV)?bb(cV):cV)}function bV(cY,c0,cW){function cX(){}cY=cX.prototype=(cY||{});var cV=new cX();var cZ={sorted:[]};b7(cV,{"this":cV,$id:(az++),$parent:cY,$bind:bF(cV,bF,cV),$get:bF(cV,bQ,cV),$set:bF(cV,cd,cV),$eval:function(c7){var c6=typeof c7;var c4,c3;var c2,c8;var c1;var c5;if(c6==q){for(c4=0,c3=cZ.sorted.length;c4<c3;c4++){for(c1=cZ.sorted[c4],c8=c1.length,c2=0;c2<c8;c2++){cV.$tryEval(c1[c2].fn,c1[c2].handler)}}}else{if(c6===bz){return c7.call(cV)}else{if(c6==="string"){return bt(c7).call(cV)}}}},$tryEval:function(c4,c1){var c2=typeof c4;try{if(c2==bz){return c4.call(cV)}else{if(c2=="string"){return bt(c4).call(cV)}}}catch(c3){(cV.$log||{error:cG}).error(c3);if(E(c1)){c1(c3)}else{if(c1){ao(c1,c3)}else{if(E(cV.$exceptionHandler)){cV.$exceptionHandler(c3)}}}}},$watch:function(c6,c5,c2,c1){var c7=bt(c6),c4=c7.call(cV);c5=bt(c5);function c3(da){var c9=c7.call(cV),c8=c4;if(da||c8!==c9){c4=c9;cV.$tryEval(function(){return c5.call(cV,c9,c8)},c2)}}cV.$onEval(an,c3);if(bB(c1)){c1=true}if(c1){c3(true)}},$onEval:function(c2,c4,c1){if(!aU(c2)){c1=c4;c4=c2;c2=0}var c3=cZ[c2];if(!c3){c3=cZ[c2]=[];c3.priority=c2;cZ.sorted.push(c3);cZ.sorted.sort(function(c6,c5){return c6.priority-c5.priority})}c3.push({fn:bt(c4),handler:c1})},$become:function(c1){if(E(c1)){cV.constructor=c1;aS(c1.prototype,function(c3,c2){cV[c2]=bF(cV,c3)});cV.$inject.apply(cV,bd([c1,cV],arguments,1));if(E(c1.prototype.init)){cV.init()}}},$new:function(c1){var c2=bV(cV);c2.$become.apply(cV,bd([c1],arguments,1));cV.$onEval(c2.$eval);return c2}});if(!cY.$root){cV.$root=cV;cV.$parent=cV;(cV.$inject=bY(cV,c0,cW))()}return cV}function bY(cW,cY,cV){cY=cY||bs;cV=cV||{};cW=cW||{};return function cX(c3,c2,c0){var c1,c4,cZ;if(ci(c3)){if(!cV.hasOwnProperty(c3)){c4=cY[c3];if(!c4){throw"Unknown provider for '"+c3+"'."}cV[c3]=cX(c4,cW)}c1=cV[c3]}else{if(a9(c3)){c1=[];aS(c3,function(c5){c1.push(cX(c5))})}else{if(E(c3)){c1=cX(c3.$inject||[]);c1=c3.apply(c2,bd(c1,arguments,2))}else{if(cR(c3)){aS(cY,function(c6,c5){cZ=c6.$creation;if(cZ=="eager"){cX(c5)}if(cZ=="eager-published"){cd(c3,c5,cX(c5))}})}else{c1=cX(cW)}}}}return c1}}var J={"null":function(cV){return a6},"true":function(cV){return true},"false":function(cV){return false},$undefined:j,"+":function(cX,cW,cV){return(cv(cW)?cW:0)+(cv(cV)?cV:0)},"-":function(cX,cW,cV){return(cv(cW)?cW:0)-(cv(cV)?cV:0)},"*":function(cX,cW,cV){return cW*cV},"/":function(cX,cW,cV){return cW/cV},"%":function(cX,cW,cV){return cW%cV},"^":function(cX,cW,cV){return cW^cV},"=":j,"==":function(cX,cW,cV){return cW==cV},"!=":function(cX,cW,cV){return cW!=cV},"<":function(cX,cW,cV){return cW<cV},">":function(cX,cW,cV){return cW>cV},"<=":function(cX,cW,cV){return cW<=cV},">=":function(cX,cW,cV){return cW>=cV},"&&":function(cX,cW,cV){return cW&&cV},"||":function(cX,cW,cV){return cW||cV},"&":function(cX,cW,cV){return cW&cV},"|":function(cX,cW,cV){return cV(cX,cW)},"!":function(cW,cV){return !cV}};var T={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'};function bq(c8,cY){var dd=cY?24:-1,da=[],c2,c1=0,df=[],c6,dh=":";while(c1<c8.length){c6=c8.charAt(c1);if(c0("\"'")){cW(c6)}else{if(c9(c6)||c0(".")&&c9(dc())){cX()}else{if(db(c6)){c7();if(c5("{,")&&df[0]=="{"&&(c2=da[da.length-1])){c2.json=c2.text.indexOf(".")==-1}}else{if(c0("(){}[].,;:")){da.push({index:c1,text:c6,json:c0("{}[]:,")});if(c0("{[")){df.unshift(c6)}if(c0("}]")){df.shift()}c1++}else{if(cZ(c6)){c1++;continue}else{var cV=c6+dc(),c3=J[c6],de=J[cV];if(de){da.push({index:c1,text:cV,fn:de});c1+=2}else{if(c3){da.push({index:c1,text:c6,fn:c3,json:c5("[,:")&&c0("+-")});c1+=1}else{dg("Unexpected next character ",c1,c1+1)}}}}}}}dh=c6}return da;function c0(di){return di.indexOf(c6)!=-1}function c5(di){return di.indexOf(dh)!=-1}function dc(){return c1+1<c8.length?c8.charAt(c1+1):false}function c9(di){return"0"<=di&&di<="9"}function cZ(di){return di==" "||di=="\r"||di=="\t"||di=="\n"||di=="\v"||di=="\u00A0"}function db(di){return"a"<=di&&di<="z"||"A"<=di&&di<="Z"||"_"==di||di=="$"}function dg(dj,dk,di){di=di||c1;throw cK("Lexer Error: "+dj+" at column"+(cv(dk)?"s "+dk+"-"+c1+" ["+c8.substring(dk,di)+"]":" "+di)+" in expression ["+c8+"].")}function c4(dm,di,dl){var dj=c8.substr(c1).match(dm);var dk={index:c1};var dn=c1;if(!dj){dg(dl)}c1+=dj[0].length;di(dk,dk.text=dj[0],dn);da.push(dk)}function cX(){c4(/^(\d+)?(\.\d+)?([eE][+-]?\d+)?/,function(di,dj){di.text=dj=1*dj;di.json=true;di.fn=cr(dj)},"Not a valid number")}function c7(){c4(/^[\w_\$][\w_\$\d]*(\.[\w_\$][\w_\$\d]*)*/,function(di,dj){c3=J[dj];if(!c3){c3=co(dj);c3.isAssignable=dj}di.fn=J[dj]||b7(co(dj),{assign:function(dk,dl){return cd(dk,dj,dl)}});di.json=J[dj]})}function cW(di){c4(/^(('(\\'|[^'])*')|("(\\"|[^"])*"))/,function(dm,dl,dn){var dj;var dk=dm.string=dl.substr(1,dl.length-2).replace(/(\\u(.?.?.?.?))|(\\(.))/g,function(dq,dt,dp,dr,ds){if(dp&&!dp.match(/[\da-fA-F]{4}/)){dj=dj||bF(null,dg,"Invalid unicode escape [\\u"+dp+"]",dn)}return dp?String.fromCharCode(parseInt(dp,16)):T[ds]||ds});(dj||j)();dm.json=true;dm.fn=function(){return(dk.length==dd)?aB.String["toDate"](dk):dk}},"Unterminated string")}}function S(dj,ds){var c9=cr(0),dm=bq(dj,ds);return{assertAllConsumed:de,primary:dc,statements:c0,validator:dt,filter:dn,watch:dd};function c7(dx,dw){throw cK("Parse Error: Token '"+dw.text+"' "+dx+" at column "+(dw.index+1)+" of expression ["+dj+"] starting at ["+dj.substring(dw.index)+"].")}function c1(){if(dm.length===0){throw cK("Unexpected end of expression: "+dj)}return dm[0]}function c3(dB,dA,dz,dy){if(dm.length>0){var dx=dm[0];var dw=dx.text;if(dw==dB||dw==dA||dw==dz||dw==dy||(!dB&&!dA&&!dz&&!dy)){return dx}}return false}function cX(dA,dz,dy,dx){var dw=c3(dA,dz,dy,dx);if(dw){if(ds&&!dw.json){index=dw.index;c7("is not valid json",dw)}dm.shift();this.currentToken=dw;return dw}return false}function dg(dw){if(!cX(dw)){c7("is unexpected, expecting ["+dw+"]",c3())}}function c8(dx,dw){return function(dy){return dx(dy,dw(dy))}}function du(dy,dx,dw){return function(dz){return dx(dz,dy(dz),dw(dz))}}function c6(){return dm.length>0}function de(){if(dm.length!==0){c7("is extra token not part of expression",dm[0])}}function c0(){var dw=[];while(true){if(dm.length>0&&!c3("}",")",";","]")){dw.push(c4())}if(!cX(";")){return function(dx){var dA;for(var dy=0;dy<dw.length;dy++){var dz=dw[dy];if(dz){dA=dz(dx)}}return dA}}}}function c4(){var dx=di();var dw;while(true){if((dw=cX("|"))){dx=du(dx,dw.fn,dn())}else{return dx}}}function dn(){return cV(cu)}function dt(){return cV(aK)}function cV(dy){var dz=cY(dy);var dw=[];var dx;while(true){if((dx=cX(":"))){dw.push(di())}else{var dA=function(dC,dB){var dD=[dB];for(var dE=0;dE<dw.length;dE++){dD.push(dw[dE](dC))}return dz.apply(dC,dD)};return function(){return dA}}}}function di(){return da()}function da(){var dy=dq();var dx;var dw;if(dw=cX("=")){if(!dy.assign){c7("implies assignment but ["+dj.substring(0,dw.index)+"] can not be assigned to",dw)}dx=dq();return function(dz){return dy.assign(dz,dx(dz))}}else{return dy}}function dq(){var dx=c5();var dw;while(true){if((dw=cX("||"))){dx=du(dx,dw.fn,c5())}else{return dx}}}function c5(){var dx=cZ();var dw;if((dw=cX("&&"))){dx=du(dx,dw.fn,c5())}return dx}function cZ(){var dx=dk();var dw;if((dw=cX("==","!="))){dx=du(dx,dw.fn,cZ())}return dx}function dk(){var dx=dl();var dw;if(dw=cX("<",">","<=",">=")){dx=du(dx,dw.fn,dk())}return dx}function dl(){var dx=cW();var dw;while(dw=cX("+","-")){dx=du(dx,dw.fn,cW())}return dx}function cW(){var dx=df();var dw;while(dw=cX("*","/","%")){dx=du(dx,dw.fn,df())}return dx}function df(){var dw;if(cX("+")){return dc()}else{if(dw=cX("-")){return du(c9,dw.fn,df())}else{if(dw=cX("!")){return c8(dw.fn,df())}else{return dc()}}}}function cY(dB){var dA=cX();var dz=dA.text.split(".");var dw=dB;var dy;for(var dx=0;dx<dz.length;dx++){dy=dz[dx];if(dw){dw=dw[dy]}}if(typeof dw!=bz){c7("should be a function",dA)}return dw}function dc(){var dy;if(cX("(")){var dz=c4();dg(")");dy=dz}else{if(cX("[")){dy=c2()}else{if(cX("{")){dy=dr()}else{var dw=cX();dy=dw.fn;if(!dy){c7("not a primary expression",dw)}}}}var dx;while(dx=cX("(","[",".")){if(dx.text==="("){dy=dh(dy)}else{if(dx.text==="["){dy=db(dy)}else{if(dx.text==="."){dy=dp(dy)}else{c7("IMPOSSIBLE")}}}}return dy}function dp(dx){var dy=cX().text;var dw=co(dy);return b7(function(dz){return dw(dx(dz))},{assign:function(dz,dA){return cd(dx(dz),dy,dA)}})}function db(dx){var dw=di();dg("]");return b7(function(dy){var dA=dx(dy);var dz=dw(dy);return(dA)?dA[dz]:cS},{assign:function(dy,dz){return dx(dy)[dw(dy)]=dz}})}function dh(dx){var dw=[];if(c1().text!=")"){do{dw.push(di())}while(cX(","))}dg(")");return function(dz){var dA=[];for(var dB=0;dB<dw.length;dB++){dA.push(dw[dB](dz))}var dy=dx(dz)||j;return dy.apply?dy.apply(dz,dA):dy(dA[0],dA[1],dA[2],dA[3],dA[4])}}function c2(){var dw=[];if(c1().text!="]"){do{dw.push(di())}while(cX(","))}dg("]");return function(dx){var dz=[];for(var dy=0;dy<dw.length;dy++){dz.push(dw[dy](dx))}return dz}}function dr(){var dw=[];if(c1().text!="}"){do{var dy=cX(),dx=dy.string||dy.text;dg(":");var dz=di();dw.push({key:dx,value:dz})}while(cX(","))}dg("}");return function(dA){var dB={};for(var dC=0;dC<dw.length;dC++){var dE=dw[dC];var dD=dE.value(dA);dB[dE.key]=dD}return dB}}function dd(){var dw=[];while(c6()){dw.push(dv());if(!cX(";")){de()}}de();return function(dx){for(var dy=0;dy<dw.length;dy++){var dz=dw[dy](dx);dx.addListener(dz.name,dz.fn)}}}function dv(){var dw=cX().text;dg(":");var dx;if(c1().text=="{"){dg("{");dx=c0();dg("}")}else{dx=di()}return function(dy){return{name:dw,fn:dx}}}}function bX(cW,cX){this.template=cW=cW+"#";this.defaults=cX||{};var cV=this.urlParams={};aS(cW.split(/\W/),function(cY){if(cY&&cW.match(new RegExp(":"+cY+"\\W"))){cV[cY]=true}})}bX.prototype={url:function(cZ){var cY=[];var cV=this;var cW=this.template;cZ=cZ||{};aS(this.urlParams,function(c1,c0){var c2=cZ[c0]||cV.defaults[c0]||"";cW=cW.replace(new RegExp(":"+c0+"(\\W)"),c2+"$1")});cW=cW.replace(/\/?#$/,"");var cX=[];ar(cZ,function(c1,c0){if(!cV.urlParams[c0]){cX.push(encodeURI(c0)+"="+encodeURI(c1))}});cW=cW.replace(/\/*$/,"");return cW+(cX.length?"?"+cX.join("&"):"")}};function bO(cV){this.xhr=cV}bO.DEFAULT_ACTIONS={get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:true},remove:{method:"DELETE"},"delete":{method:"DELETE"}};bO.prototype={route:function(cY,cZ,c1){var cW=this;var cV=new bX(cY);c1=b7({},bO.DEFAULT_ACTIONS,c1);function cX(c3){var c2={};aS(cZ||{},function(c5,c4){c2[c4]=c5.charAt&&c5.charAt(0)=="@"?bQ(c3,c5.substr(1)):c5});return c2}function c0(c2){bv(c2||{},this)}aS(c1,function(c4,c3){var c2=c4.method=="POST"||c4.method=="PUT";c0[c3]=function(c6,c5,db){var c9={};var c8;var da=j;switch(arguments.length){case 3:da=db;case 2:if(E(c5)){da=c5}else{c9=c6;c8=c5;break}case 1:if(E(c6)){da=c6}else{if(c2){c8=c6}else{c9=c6}}break;case 0:break;default:throw"Expected between 0-3 arguments [params, data, callback], got "+arguments.length+" arguments."}var c7=this instanceof c0?this:(c4.isArray?[]:new c0(c8));cW.xhr(c4.method,cV.url(b7({},c4.params||{},cX(c8),c9)),c8,function(dd,de,dc){if(dd==200){if(c4.isArray){c7.length=0;aS(de,function(df){c7.push(new c0(df))})}else{bv(de,c7)}(da||j)(c7)}else{throw {status:dd,response:de,message:dd+": "+de}}},c4.verifyCache);return c7};c0.bind=function(c5){return cW.route(cY,b7({},cZ,c5),c1)};c0.prototype["$"+c3]=function(c6,c5){var c8=cX(this);var c9=j;switch(arguments.length){case 2:c8=c6;c9=c5;case 1:if(typeof c6==bz){c9=c6}else{c8=c6}case 0:break;default:throw"Expected between 1-2 arguments [params, callback], got "+arguments.length+" arguments."}var c7=c2?this:cS;c0[c3].call(this,c8,c7,c9)}});return c0}};var L=bU.XMLHttpRequest||function(){try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(cX){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(cW){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(cV){}throw new cK("This browser does not support XMLHttpRequest.")};function aO(c7,c5,c6,c3,da,c2){var c8=this;c8.isMock=false;var cZ=0;var c1=0;var c9=[];function c4(db){try{db.apply(null,ad.call(arguments,1))}finally{c1--;if(c1===0){while(c9.length){try{c9.pop()()}catch(dc){da.error(dc)}}}}}c8.xhr=function(dh,dc,dd,dg){if(E(dd)){dg=dd;dd=a6}if(am(dh)=="json"){var de="angular_"+Math.random()+"_"+(cZ++);de=de.replace(/\d\./,"");var db=c5[0].createElement("script");db.type="text/javascript";db.src=dc.replace("JSON_CALLBACK",de);bU[de]=function(di){bU[de]=cS;dg(200,di)};c6.append(db)}else{var df=new c3();df.open(dh,dc,true);df.setRequestHeader("Content-Type","application/x-www-form-urlencoded");df.setRequestHeader("Accept","application/json, text/plain, */*");df.setRequestHeader("X-Requested-With","XMLHttpRequest");c1++;df.onreadystatechange=function(){if(df.readyState==4){c4(dg,df.status||200,df.responseText)}};df.send(dd||"")}};c8.notifyWhenNoOutstandingRequests=function(db){if(c1===0){db()}else{c9.push(db)}};var cY=[];c8.poll=function(){aS(cY,function(db){db()})};c8.addPollFn=function(db){cY.push(db);return db};c8.startPoller=function(dc,dd){(function db(){c8.poll();dd(db,dc)})()};c8.setUrl=function(dc){var db=c7.href;if(!db.match(/#/)){db+="#"}if(!dc.match(/#/)){dc+="#"}c7.href=dc};c8.getUrl=function(){return c7.href};var cV=c5[0];var cX={};var cW="";c8.cookies=function(dc,de){var dg,db,dd,df;if(dc){if(de===cS){cV.cookie=escape(dc)+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT"}else{if(ci(de)){cV.cookie=escape(dc)+"="+escape(de);dg=dc.length+de.length+1;if(dg>4096){da.warn("Cookie '"+dc+"' possibly not set or overflowed because it was too large ("+dg+" > 4096 bytes)!")}if(cX.length>20){da.warn("Cookie '"+dc+"' possibly not set or overflowed because too many cookies were already set ("+cX.length+" > 20 )")}}}}else{if(cV.cookie!==cW){cW=cV.cookie;db=cW.split("; ");cX={};for(dd=0;dd<db.length;dd++){df=db[dd].split("=");if(df.length===2){cX[unescape(df[0])]=unescape(df[1])}}}return cX}};c8.defer=function(db){c1++;c2(function(){c4(db)},0)};var c0=j;c8.hover=function(db){c0=db};c8.bind=function(){c5.bind("mouseover",function(db){c0(ck(at?db.srcElement:db.target),true);return true});c5.bind("mouseleave mouseout click dblclick keypress keyup",function(db){c0(ck(db.target),false);return true})};c8.addCss=function(db){var dc=ck(cV.createElement("link"));dc.attr("rel","stylesheet");dc.attr("type","text/css");dc.attr("href",db);c6.append(dc)};c8.addJs=function(dd,dc){var db=ck(cV.createElement("script"));db.attr("type","text/javascript");db.attr("src",dd);if(dc){db.attr("id",dc)}c6.append(db)}}var b6=/^<\s*([\w:]+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,n=/^<\s*\/\s*([\w:]+)[^>]*>/,cs=/(\w+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,cy=/^</,g=/^<\s*\//,aD=/<!--(.*?)-->/g,bW=/<!\[CDATA\[(.*?)]]>/g,bC=/^((ftp|https?):\/\/|mailto:|#)/,bh=/([^\#-~| |!])/g;var aV=cF("area,br,col,hr,img");var b2=cF("address,blockquote,center,dd,del,dir,div,dl,dt,hr,ins,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");var al=cF("a,abbr,acronym,b,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,q,s,samp,small,span,strike,strong,sub,sup,tt,u,var");var K=cF("colgroup,dd,dt,li,p,td,tfoot,th,thead,tr");var bP=cF("script,style");var bx=b7({},aV,b2,al,K);var a1=cF("compact,ismap,nohref,nowrap");var cJ=cF("background,href,longdesc,src,usemap");var a8=b7({},a1,cJ,cF("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,coords,dir,face,headers,height,hreflang,hspace,lang,language,rel,rev,rows,rowspan,rules,scope,scrolling,shape,span,start,summary,target,title,type,valign,value,vspace,width"));function aQ(cW,c4){var cZ,c0,cX,c1=[],c2=cW;c1.last=function(){return c1[c1.length-1]};while(cW){c0=true;if(!c1.last()||!bP[c1.last()]){if(cW.indexOf("<!--")===0){cZ=cW.indexOf("-->");if(cZ>=0){if(c4.comment){c4.comment(cW.substring(4,cZ))}cW=cW.substring(cZ+3);c0=false}}else{if(g.test(cW)){cX=cW.match(n);if(cX){cW=cW.substring(cX[0].length);cX[0].replace(n,cY);c0=false}}else{if(cy.test(cW)){cX=cW.match(b6);if(cX){cW=cW.substring(cX[0].length);cX[0].replace(b6,cV);c0=false}}}}if(c0){cZ=cW.indexOf("<");var c3=cZ<0?cW:cW.substring(0,cZ);cW=cZ<0?"":cW.substring(cZ);c4.chars(aa(c3))}}else{cW=cW.replace(new RegExp("(.*)<\\s*\\/\\s*"+c1.last()+"[^>]*>","i"),function(c5,c6){c6=c6.replace(aD,"$1").replace(bW,"$1");c4.chars(aa(c6));return""});cY("",c1.last())}if(cW==c2){throw"Parse Error: "+cW}c2=cW}cY();function cV(c5,c8,c9,c6){c8=am(c8);if(b2[c8]){while(c1.last()&&al[c1.last()]){cY("",c1.last())}}if(K[c8]&&c1.last()==c8){cY("",c8)}c6=aV[c8]||!!c6;if(!c6){c1.push(c8)}var c7={};c9.replace(cs,function(db,da){var dc=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:a1[da]?da:"";c7[da]=aa(dc)});c4.start(c8,c7,c6)}function cY(c5,c7){var c8=0,c6;c7=am(c7);if(c7){for(c8=c1.length-1;c8>=0;c8--){if(c1[c8]==c7){break}}}if(c8>=0){for(c6=c1.length-1;c6>=c8;c6--){c4.end(c1[c6])}c1.length=c8}}}function cF(cY){var cX={},cV=cY.split(","),cW;for(cW=0;cW<cV.length;cW++){cX[cV[cW]]=true}return cX}var y=r.createElement("pre");function aa(cV){y.innerHTML=cV.replace(/</g,"<");return y.innerText||y.textContent}function aF(cV){return cV.replace(/&/g,"&").replace(bh,function(cW){return"&#"+cW.charCodeAt(0)+";"}).replace(/</g,"<").replace(/>/g,">")}function a5(cW){var cX=false;var cV=bF(cW,cW.push);return{start:function(cY,c0,cZ){cY=am(cY);if(!cX&&bP[cY]){cX=cY}if(!cX&&bx[cY]==true){cV("<");cV(cY);aS(c0,function(c2,c1){var c3=am(c1);if(a8[c3]==true&&(cJ[c3]!==true||c2.match(bC))){cV(" ");cV(c1);cV('="');cV(aF(c2));cV('"')}});cV(cZ?"/>":">")}},end:function(cY){cY=am(cY);if(!cX&&bx[cY]==true){cV("</");cV(cY);cV(">")}if(cY==cX){cX=false}},chars:function(cY){if(!cX){cV(aF(cY))}}}}var cc={},cB="ng-"+new Date().getTime(),aj=1,aC=(bU.document.attachEvent?function(cV,cX,cW){cV.attachEvent("on"+cX,cW)}:function(cV,cX,cW){cV.addEventListener(cX,cW,false)}),e=(bU.document.detachEvent?function(cV,cX,cW){cV.detachEvent("on"+cX,cW)}:function(cV,cX,cW){cV.removeEventListener(cX,cW,false)});function cf(){return(aj++)}function cU(cW){var cX=cW[cB],cV=cc[cX];if(cV){aS(cV.bind||{},function(cZ,cY){e(cW,cY,cZ)});delete cc[cX];if(at){cW[cB]=""}else{delete cW[cB]}}}function cb(cX){var c0={},cY=cX[0].style,cZ,cV,cW;if(typeof cY.length=="number"){for(cW=0;cW<cY.length;cW++){cV=cY[cW];c0[cV]=cY[cV]}}else{for(cV in cY){cZ=cY[cV];if(1*cV!=cV&&cV!="cssText"&&cZ&&typeof cZ=="string"&&cZ!="false"){c0[cV]=cZ}}}return c0}function bu(cW){if(bJ(cW)){this[0]=cW;this.length=1}else{if(cv(cW.length)&&cW.item){for(var cV=0;cV<cW.length;cV++){this[cV]=cW[cV]}this.length=cW.length}}}bu.prototype={data:function(cX,cY){var cW=this[0],cZ=cW[cB],cV=cc[cZ||-1];if(cv(cY)){if(!cV){cW[cB]=cZ=cf();cV=cc[cZ]={}}cV[cX]=cY}else{return cV?cV[cX]:a6}},removeData:function(){cU(this[0])},dealoc:function(){(function cV(cY){cU(cY);for(var cX=0,cW=cY.childNodes;cX<cW.length;cX++){cV(cW[cX])}})(this[0])},bind:function(cZ,cY){var cV=this,cX=cV[0],c0=cV.data("bind"),cW;if(!c0){this.data("bind",c0={})}aS(cZ.split(" "),function(c1){cW=c0[c1];if(!cW){c0[c1]=cW=function(c2){if(!c2.preventDefault){c2.preventDefault=function(){c2.returnValue=false}}if(!c2.stopPropagation){c2.stopPropagation=function(){c2.cancelBubble=true}}aS(cW.fns,function(c3){c3.call(cV,c2)})};cW.fns=[];aC(cX,c1,cW)}cW.fns.push(cY)})},replaceWith:function(cV){this[0].parentNode.replaceChild(ck(cV)[0],this[0])},children:function(){return new bu(this[0].childNodes)},append:function(cW){var cV=this[0];cW=ck(cW);aS(cW,function(cX){cV.appendChild(cX)})},remove:function(){this.dealoc();var cV=this[0].parentNode;if(cV){cV.removeChild(this[0])}},removeAttr:function(cV){this[0].removeAttribute(cV)},after:function(cV){this[0].parentNode.insertBefore(ck(cV)[0],this[0].nextSibling)},hasClass:function(cV){var cW=" "+cV+" ";if((" "+this[0].className+" ").replace(/[\n\t]/g," ").indexOf(cW)>-1){return true}return false},removeClass:function(cV){this[0].className=av((" "+this[0].className+" ").replace(/[\n\t]/g," ").replace(" "+cV+" ",""))},toggleClass:function(cV,cX){var cW=this;(cX?cW.addClass:cW.removeClass).call(cW,cV)},addClass:function(cV){if(!this.hasClass(cV)){this[0].className=av(this[0].className+" "+cV)}},css:function(cV,cX){var cW=this[0].style;if(ci(cV)){if(cv(cX)){cW[cV]=cX}else{return cW[cV]}}else{b7(cW,cV)}},attr:function(cV,cW){var cX=this[0];if(cR(cV)){aS(cV,function(cZ,cY){cX.setAttribute(cY,cZ)})}else{if(cv(cW)){cX.setAttribute(cV,cW)}else{return cX.getAttribute(cV,2)}}},text:function(cV){if(cv(cV)){this[0].textContent=cV}return this[0].textContent},val:function(cV){if(cv(cV)){this[0].value=cV}return this[0].value},html:function(cW){if(cv(cW)){var cV=0,cX=this[0].childNodes;for(;cV<cX.length;cV++){ck(cX[cV]).dealoc()}this[0].innerHTML=cW}return this[0].innerHTML},parent:function(){return ck(this[0].parentNode)},clone:function(){return ck(this[0].cloneNode(true))}};if(at){b7(bu.prototype,{text:function(cV){var cW=this[0];if(cW.nodeType==3){if(cv(cV)){cW.nodeValue=cV}return cW.nodeValue}else{if(cv(cV)){cW.innerText=cV}return cW.innerText}}})}var aY={typeOf:function(cW){if(cW===a6){return v}var cV=typeof cW;if(cV==aP){if(cW instanceof Array){return a3}if(ax(cW)){return bc}if(cW.nodeType==1){return cC}}return cV}};var cQ={copy:bv,size:aw,equals:p};var bk={extend:b7};var M={indexOf:cO,sum:function(c0,cZ){var cX=aB.Function["compile"](cZ);var cW=0;for(var cV=0;cV<c0.length;cV++){var cY=1*cX(c0[cV]);if(!isNaN(cY)){cW+=cY}}return cW},remove:function(cX,cW){var cV=cO(cX,cW);if(cV>=0){cX.splice(cV,1)}return cW},filter:function(c2,c1){var cX=[];cX.check=function(c4){for(var c3=0;c3<cX.length;c3++){if(!cX[c3](c4)){return false}}return true};var cZ=function(c5,c6){if(c6.charAt(0)==="!"){return !cZ(c5,c6.substr(1))}switch(typeof c5){case"boolean":case"number":case"string":return(""+c5).toLowerCase().indexOf(c6)>-1;case"object":for(var c4 in c5){if(c4.charAt(0)!=="$"&&cZ(c5[c4],c6)){return true}}return false;case"array":for(var c3=0;c3<c5.length;c3++){if(cZ(c5[c3],c6)){return true}}return false;default:return false}};switch(typeof c1){case"boolean":case"number":case"string":c1={$:c1};case"object":for(var cY in c1){if(cY=="$"){(function(){var c3=(""+c1[cY]).toLowerCase();if(!c3){return}cX.push(function(c4){return cZ(c4,c3)})})()}else{(function(){var c3=cY;var c4=(""+c1[cY]).toLowerCase();if(!c4){return}cX.push(function(c5){return cZ(bQ(c5,c3),c4)})})()}}break;case bz:cX.push(c1);break;default:return c2}var cW=[];for(var cV=0;cV<c2.length;cV++){var c0=c2[cV];if(cX.check(c0)){cW.push(c0)}}return cW},add:function(cW,cV){cW.push(bB(cV)?{}:cV);return cW},count:function(cY,cX){if(!cX){return cY.length}var cV=aB.Function["compile"](cX),cW=0;aS(cY,function(cZ){if(cV(cZ)){cW++}});return cW},orderBy:function(c2,c1,cZ){c1=a9(c1)?c1:[c1];c1=aI(c1,function(c4){var c5=false,c3=c4||aG;if(ci(c4)){if((c4.charAt(0)=="+"||c4.charAt(0)=="-")){c5=c4.charAt(0)=="-";c4=c4.substring(1)}c3=bt(c4).fnSelf}return cW(function(c7,c6){return c0(c3(c7),c3(c6))},c5)});var cY=[];for(var cX=0;cX<c2.length;cX++){cY.push(c2[cX])}return cY.sort(cW(cV,cZ));function cV(c6,c5){for(var c4=0;c4<c1.length;c4++){var c3=c1[c4](c6,c5);if(c3!==0){return c3}}return 0}function cW(c3,c4){return cp(c4)?function(c6,c5){return c3(c5,c6)}:c3}function c0(c6,c5){var c4=typeof c6;var c3=typeof c5;if(c4==c3){if(c4=="string"){c6=c6.toLowerCase()}if(c4=="string"){c5=c5.toLowerCase()}if(c6===c5){return 0}return c6<c5?-1:1}else{return c4<c3?-1:1}}},limitTo:function(cZ,cV){cV=parseInt(cV,10);var cW=[],cX,cY;if(cV>0){cX=0;cY=cV}else{cX=cZ.length+cV;cY=cZ.length}for(;cX<cY;cX++){cW.push(cZ[cX])}return cW}};var a7=/^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d)(?:\:(\d\d)(?:\:(\d\d)(?:\.(\d{3}))?)?)?Z)?$/;var aq={quote:function(cV){return'"'+cV.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\v/g,"\\v")+'"'},quoteUnicode:function(cV){var c0=aB.String["quote"](cV);var cZ=[];for(var cW=0;cW<c0.length;cW++){var cX=c0.charCodeAt(cW);if(cX<128){cZ.push(c0.charAt(cW))}else{var cY="000"+cX.toString(16);cZ.push("\\u"+cY.substring(cY.length-4))}}return cZ.join("")},toDate:function(cX){var cW;if(ci(cX)&&(cW=cX.match(a7))){var cV=new Date(0);cV.setUTCFullYear(cW[1],cW[2]-1,cW[3]);cV.setUTCHours(cW[4]||0,cW[5]||0,cW[6]||0,cW[7]||0);return cV}return cX}};var af={toString:function(cV){return !cV?cV:cV.toISOString?cV.toISOString():cn(cV.getUTCFullYear(),4)+"-"+cn(cV.getUTCMonth()+1,2)+"-"+cn(cV.getUTCDate(),2)+"T"+cn(cV.getUTCHours(),2)+":"+cn(cV.getUTCMinutes(),2)+":"+cn(cV.getUTCSeconds(),2)+"."+cn(cV.getUTCMilliseconds(),3)+"Z"}};var w={compile:function(cV){if(E(cV)){return cV}else{if(cV){return bt(cV).fnSelf}else{return aG}}}};function I(cW,cV){aB[cW]=aB[cW]||{};aS(cV,function(cX){b7(aB[cW],cX)})}I("Global",[aY]);I("Collection",[aY,cQ]);I("Array",[aY,cQ,M]);I("Object",[aY,cQ,bk]);I("String",[aY,aq]);I("Date",[aY,af]);aB.Date["toString"]=af.toString;I("Function",[aY,cQ,w]);cu.currency=function(cV){this.$element.toggleClass("ng-format-negative",cV<0);return"$"+cu.number.apply(this,[cV,2])};cu.number=function(cY,cV){if(isNaN(cY)||!isFinite(cY)){return""}cV=typeof cV==q?2:cV;var cW=cY<0;cY=Math.abs(cY);var c1=Math.pow(10,cV);var c3=""+Math.round(cY*c1);var c2=c3.substring(0,c3.length-cV);c2=c2||"0";var cX=c3.substring(c3.length-cV);c3=cW?"-":"";for(var c0=0;c0<c2.length;c0++){if((c2.length-c0)%3===0&&c0!==0){c3+=","}c3+=c2.charAt(c0)}if(cV>0){for(var cZ=cX.length;cZ<cV;cZ++){cX+="0"}c3+="."+cX.substring(0,cV)}return c3};function cn(cW,cX,cV){var cY="";if(cW<0){cY="-";cW=-cW}cW=""+cW;while(cW.length<cX){cW="0"+cW}if(cV){cW=cW.substr(cW.length-cX)}return cY+cW}function br(cW,cX,cY,cV){return function(cZ){var c0=cZ["get"+cW]();if(cY>0||c0>-cY){c0+=cY}if(c0===0&&cY==-12){c0=12}return cn(c0,cX,cV)}}var bG={yyyy:br("FullYear",4),yy:br("FullYear",2,0,true),MM:br("Month",2,1),M:br("Month",1,1),dd:br("Date",2),d:br("Date",1),HH:br("Hours",2),H:br("Hours",1),hh:br("Hours",2,-12),h:br("Hours",1,-12),mm:br("Minutes",2),m:br("Minutes",1),ss:br("Seconds",2),s:br("Seconds",1),a:function(cV){return cV.getHours()<12?"am":"pm"},Z:function(cV){var cW=cV.getTimezoneOffset();return cn(cW/60,2)+cn(Math.abs(cW%60),2)}};var ap=/([^yMdHhmsaZ]*)(y+|M+|d+|H+|h+|m+|s+|a|Z)(.*)/;var cq=/^\d+$/;cu.date=function(cV,cY){if(ci(cV)){if(cq.test(cV)){cV=parseInt(cV,10)}else{cV=aq.toDate(cV)}}if(aU(cV)){cV=new Date(cV)}if(!ax(cV)){return cV}var cZ=cV.toLocaleDateString(),cW;if(cY&&ci(cY)){cZ="";var cX=[];while(cY){cX=bd(cX,ap.exec(cY),1);cY=cX.pop()}aS(cX,function(c0){cW=bG[c0];cZ+=cW?cW(cV):c0})}return cZ};cu.json=function(cV){this.$element.addClass("ng-monospace");return cm(cV,true)};cu.lowercase=am;cu.uppercase=bI;cu.html=function(cV,cW){return new aW(cV,cW)};cu.linky=function(c2){if(!c2){return c2}var cV=/((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/;var cY;var cX=c2;var c0=[];var c1=a5(c0);var cW;var cZ;while(cY=cX.match(cV)){cW=cY[0];if(cY[2]==cY[3]){cW="mailto:"+cW}cZ=cY.index;c1.chars(cX.substr(0,cZ));c1.start("a",{href:cW});c1.chars(cY[0].replace(/^mailto:/,""));c1.end("a");cX=cX.substring(cZ+cY[0].length)}c1.chars(cX);return new aW(c0.join(""))};function a0(cV,cW){return{format:cV,parse:cW||cV}}function D(cV){return(cv(cV)&&cV!==a6)?""+cV:cV}var aT=/^\s*[-+]?\d*(\.\d*)?\s*$/;l.noop=a0(aG,aG);l.json=a0(cm,Q);l["boolean"]=a0(D,cp);l.number=a0(D,function(cV){if(cV==a6||aT.exec(cV)){return cV===a6||cV===""?a6:1*cV}else{throw"Not a number"}});l.list=a0(function(cV){return cV?cV.join(", "):cV},function(cW){var cV=[];aS((cW||"").split(","),function(cX){cX=av(cX);if(cX){cV.push(cX)}});return cV});l.trim=a0(function(cV){return cV?av(""+cV):""});b7(aK,{noop:function(){return a6},regexp:function(cW,cV,cX){if(!cW.match(cV)){return cX||"Value does not match expected format "+cV+"."}else{return a6}},number:function(cY,cX,cV){var cW=1*cY;if(cW==cY){if(typeof cX!=q&&cW<cX){return"Value can not be less than "+cX+"."}if(typeof cX!=q&&cW>cV){return"Value can not be greater than "+cV+"."}return a6}else{return"Not a number"}},integer:function(cY,cW,cV){var cX=aK.number(cY,cW,cV);if(cX){return cX}if(!(""+cY).match(/^\s*[\d+]*\s*$/)||cY!=Math.round(cY)){return"Not a whole number"}return a6},date:function(cX){var cV=/^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(cX);var cW=cV?new Date(cV[3],cV[1]-1,cV[2]):0;return(cW&&cW.getFullYear()==cV[3]&&cW.getMonth()==cV[1]-1&&cW.getDate()==cV[2])?a6:"Value is not a date. (Expecting format: 12/31/2009)."},email:function(cV){if(cV.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)){return a6}return"Email needs to be in [email protected] format."},phone:function(cV){if(cV.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)){return a6}if(cV.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)){return a6}return"Phone number needs to be in 1(987)654-3210 format in North America or +999 (123) 45678 906 internationaly."},url:function(cV){if(cV.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)){return a6}return"URL needs to be in http://server[:port]/path format."},json:function(cV){try{Q(cV);return a6}catch(cW){return cW.toString()}},asynchronous:function(cY,c1,cW){if(!cY){return}var c0=this;var cZ=c0.$element;var cX=cZ.data("$asyncValidator");if(!cX){cZ.data("$asyncValidator",cX={inputs:{}})}cX.current=cY;var cV=cX.inputs[cY];if(!cV){cX.inputs[cY]=cV={inFlight:true};c0.$invalidWidgets.markInvalid(c0.$element);cZ.addClass("ng-input-indicator-wait");c1(cY,function(c2,c3){cV.response=c3;cV.error=c2;cV.inFlight=false;if(cX.current==cY){cZ.removeClass("ng-input-indicator-wait");c0.$invalidWidgets.markValid(cZ)}cZ.data(bf)();c0.$root.$eval()})}else{if(cV.inFlight){c0.$invalidWidgets.markInvalid(c0.$element)}else{(cW||j)(cV.response)}}return cV.error}});var H=/^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,z=/^([^\?]*)?(\?([^\?]*))?$/,cA={http:80,https:443,ftp:21},bT="eager",bK=bT+"-published";function cl(cW,cY,cX,cV){bs(cW,cY,{$inject:cX,$creation:cV})}cl("$window",bF(bU,aG,bU),[],bK);cl("$document",function(cV){return ck(cV.document)},["$window"],bK);cl("$location",function(c2){var da=this,c6={toString:cW,update:c1,updateHash:c5},c0=c2.getUrl(),cY,c3;c2.addPollFn(function(){if(c0!=c2.getUrl()){c1(c0=c2.getUrl());c9();da.$eval()}});this.$onEval(bp,c4);this.$onEval(cg,c4);c1(c0);c9();return c6;function c1(db){if(ci(db)){b7(c6,c8(db))}else{if(cv(db.hash)){b7(db,cZ(db.hash))}b7(c6,db);if(cv(db.hashPath||db.hashSearch)){c6.hash=cX(c6)}c6.href=c7(c6)}}function c5(dd,db){var dc={};if(ci(dd)){dc.hashPath=dd;if(cv(db)){dc.hashSearch=db}}else{dc.hashSearch=dd}c1(dc)}function cW(){cV();return c6.href}function cV(){if(c6.href==cY){if(c6.hash==c3){c6.hash=cX(c6)}c6.href=c7(c6)}c1(c6.href)}function c9(){cY=c6.href;c3=c6.hash}function c4(){cV();if(c6.href!=cY){c2.setUrl(c0=c6.href);c9()}}function c7(dd){var dc=N(dd.search);var db=(dd.port==cA[dd.protocol]?a6:dd.port);return dd.protocol+"://"+dd.host+(db?":"+db:"")+dd.path+(dc?"?"+dc:"")+(dd.hash?"#"+dd.hash:"")}function cX(dc){var db=N(dc.hashSearch);return escape(dc.hashPath).replace(/%21/gi,"!").replace(/%3A/gi,":").replace(/%24/gi,"$")+(db?"?"+db:"")}function c8(db){var dd={};var dc=H.exec(db);if(dc){dd.href=db.replace(/#$/,"");dd.protocol=dc[1];dd.host=dc[3]||"";dd.port=dc[5]||cA[dd.protocol]||a6;dd.path=dc[6]||"";dd.search=ah(dc[8]);dd.hash=dc[10]||"";b7(dd,cZ(dd.hash))}return dd}function cZ(dd){var dc={};var db=z.exec(dd);if(db){dc.hash=dd;dc.hashPath=unescape(db[1]||"");dc.hashSearch=ah(db[3])}return dc}},["$browser"],bK);cl("$log",function(cW){return{log:cV("log"),warn:cV("warn"),info:cV("info"),error:cV("error")};function cV(cY){var cX=cW.console||{};var cZ=cX[cY]||cX.log||j;if(cZ.apply){return function(){var c0=[];aS(arguments,function(c1){c0.push(bb(c1))});return cZ.apply(cX,c0)}}else{return cZ}}},["$window"],bK);cl("$exceptionHandler",function(cV){return function(cW){cV.error(cW)}},["$log"],bK);cl("$hover",function(c0,cW){var c2,cY=this,cZ,c1=300,cX=10,cV=ck(cW[0].body);c0.hover(function(c6,c4){if(c4&&(cZ=c6.attr(a)||c6.attr(k))){if(!c2){c2={callout:ck('<div id="ng-callout"></div>'),arrow:ck("<div></div>"),title:ck('<div class="ng-title"></div>'),content:ck('<div class="ng-content"></div>')};c2.callout.append(c2.arrow);c2.callout.append(c2.title);c2.callout.append(c2.content);cV.append(c2.callout)}var c3=cV[0].getBoundingClientRect(),c5=c6[0].getBoundingClientRect(),c7=c3.right-c5.right-cX;c2.title.text(c6.hasClass("ng-exception")?"EXCEPTION:":"Validation error...");c2.content.text(cZ);if(c7<c1){c2.arrow.addClass("ng-arrow-right");c2.arrow.css({left:(c1+1)+"px"});c2.callout.css({position:"fixed",left:(c5.left-cX-c1-4)+"px",top:(c5.top-3)+"px",width:c1+"px"})}else{c2.arrow.addClass("ng-arrow-left");c2.callout.css({position:"fixed",left:(c5.right+cX)+"px",top:(c5.top-3)+"px",width:c1+"px"})}}else{if(c2){c2.callout.remove();c2=a6}}})},["$browser","$document"],bT);cl("$invalidWidgets",function(){var cW=[];cW.markValid=function(cY){var cX=cO(cW,cY);if(cX!=-1){cW.splice(cX,1)}};cW.markInvalid=function(cY){var cX=cO(cW,cY);if(cX===-1){cW.push(cY)}};cW.visible=function(){var cX=0;aS(cW,function(cY){cX=cX+(aR(cY)?1:0)});return cX};this.$onEval(cg,function(){for(var cX=0;cX<cW.length;){var cY=cW[cX];if(cV(cY[0])){cW.splice(cX,1);if(cY.dealoc){cY.dealoc()}}else{cX++}}});function cV(cY){if(cY==bU.document){return false}var cX=cY.parentNode;return !cX||cV(cX)}return cW},[],bK);function bj(cW,cV,cZ){var cY="^"+cV.replace(/[\.\\\(\)\^\$]/g,"$1")+"$",c0=[],c1={};aS(cV.split(/\W/),function(c3){if(c3){var c2=new RegExp(":"+c3+"([\\W])");if(cY.match(c2)){cY=cY.replace(c2,"([^/]*)$1");c0.push(c3)}}});var cX=cW.match(new RegExp(cY));if(cX){aS(c0,function(c3,c2){c1[c3]=cX[c2+1]});if(cZ){this.$set(cZ,c1)}}return cX?c1:a6}cl("$route",function(cW){var cV={},cX=[],c1=bj,cZ=this,cY=0,c2={routes:cV,onChange:bF(cX,cX.push),when:function(c4,c5){if(aB.isUndefined(c4)){return cV}var c3=cV[c4];if(!c3){c3=cV[c4]={}}if(c5){aB.extend(c3,c5)}cY++;return c3}};function c0(){var c3;c2.current=a6;aB.foreach(cV,function(c4,c5){if(!c3){var c6=c1(cW.hashPath,c5);if(c6){c3=aB.scope(cZ);c2.current=aB.extend({},c4,{scope:c3,params:aB.extend({},cW.hashSearch,c6)})}}});aB.foreach(cX,cZ.$tryEval);if(c3){c3.$become(c2.current.controller)}}this.$watch(function(){return cY+cW.hash},c0);return c2},["$location"],bK);cl("$xhr",function(cW,cV,cY){var cX=this;return function(c2,cZ,c0,c1){if(E(c0)){c1=c0;c0=a6}if(c0&&cR(c0)){c0=cm(c0)}cW.xhr(c2,cZ,c0,function(c4,c3){try{if(ci(c3)&&/^\s*[\[\{]/.exec(c3)&&/[\}\]]\s*$/.exec(c3)){c3=Q(c3)}if(c4==200){c1(c4,c3)}else{cV({method:c2,url:cZ,data:c0,callback:c1},{status:c4,body:c3})}}catch(c5){cY.error(c5)}finally{cX.$eval()}})}},["$browser","$xhr.error","$log"]);cl("$xhr.error",function(cV){return function(cX,cW){cV.error("ERROR: XHR: "+cX.url,cX,cW)}},["$log"]);cl("$xhr.bulk",function(cW,cV,cZ){var c0=[],cY=this;function cX(c5,c1,c2,c4){if(E(c2)){c4=c2;c2=a6}var c3;aS(cX.urls,function(c6){if(E(c6.match)?c6.match(c1):c6.match.exec(c1)){c3=c6}});if(c3){if(!c3.requests){c3.requests=[]}c3.requests.push({method:c5,url:c1,data:c2,callback:c4})}else{cW(c5,c1,c2,c4)}}cX.urls={};cX.flush=function(c1){aS(cX.urls,function(c2,c3){var c4=c2.requests;if(c4&&c4.length){c2.requests=[];c2.callbacks=[];cW("POST",c3,{requests:c4},function(c6,c5){aS(c5,function(c7,c8){try{if(c7.status==200){(c4[c8].callback||j)(c7.status,c7.response)}else{cV(c4[c8],c7)}}catch(c9){cZ.error(c9)}});(c1||j)()});cY.$eval()}})};this.$onEval(cg,cX.flush);return cX},["$xhr","$xhr.error","$log"]);cl("$defer",function(cV,cW){var cX=this;return function(cY){cV.defer(function(){try{cY()}catch(cZ){cW(cZ)}finally{cX.$eval()}})}},["$browser","$exceptionHandler"]);cl("$xhr.cache",function(cV,cY){var cZ={},cX=this;function cW(c6,c0,c1,c5,c4){if(E(c1)){c5=c1;c1=a6}if(c6=="GET"){var c3,c2;if(c2=cW.data[c0]){cY(function(){c5(200,bv(c2.value))});if(!c4){return}}if(c3=cZ[c0]){c3.callbacks.push(c5)}else{cZ[c0]={callbacks:[c5]};cW.delegate(c6,c0,c1,function(c7,c8){if(c7==200){cW.data[c0]={value:c8}}var c9=cZ[c0].callbacks;delete cZ[c0];aS(c9,function(db){try{(db||j)(c7,bv(c8))}catch(da){cX.$log.error(da)}})})}}else{cW.data={};cW.delegate(c6,c0,c1,c5)}}cW.data={};cW.delegate=cV;return cW},["$xhr.bulk","$defer"]);cl("$resource",function(cV){var cW=new bO(cV);return bF(cW,cW.route)},["$xhr.cache"]);cl("$cookies",function(cW){var cZ=this,c0={},cX={},cV;cW.addPollFn(function(){var c1=cW.cookies();if(cV!=c1){cV=c1;bv(c1,cX);bv(c1,c0);cZ.$eval()}})();this.$onEval(cg,cY);return c0;function cY(){var c2,c3,c1;for(c2 in cX){if(bB(c0[c2])){cW.cookies(c2,cS)}}for(c2 in c0){if(c0[c2]!==cX[c2]){cW.cookies(c2,c0[c2]);c1=true}}if(c1){c1=!c1;c3=cW.cookies();for(c2 in c0){if(c0[c2]!==c3[c2]){if(bB(c3[c2])){delete c0[c2]}else{c0[c2]=c3[c2]}c1=true}}if(c1){cZ.$eval()}}}},["$browser"],bK);cl("$cookieStore",function(cV){return{get:function(cW){return Q(cV[cW])},put:function(cW,cX){cV[cW]=cm(cX)},remove:function(cW){delete cV[cW]}}},["$cookies"]);Z("ng:init",function(cV){return function(cW){this.$tryEval(cV,cW)}});Z("ng:controller",function(cV){this.scope(true);return function(cX){var cW=bQ(bU,cV,true)||bQ(this,cV,true);if(!cW){throw"Can not find '"+cV+"' controller."}if(!E(cW)){throw"Reference '"+cV+"' is not a class."}this.$become(cW)}});Z("ng:eval",function(cV){return function(cW){this.$onEval(cV,cW)}});Z("ng:bind",function(cW,cV){cV.addClass("ng-binding");return function(cY){var cX=j,cZ=j;this.$onEval(function(){var c1,c5,c2,c3,c4,c0=this.hasOwnProperty(by)?this.$element:cS;this.$element=cY;c5=this.$tryEval(cW,function(c6){c1=bb(c6)});this.$element=c0;if(c3=(c5 instanceof aW)){c5=(c2=c5).html}if(cX===c5&&cZ==c1){return}c4=bJ(c5);if(!c3&&!c4&&cR(c5)){c5=cm(c5)}if(c5!=cX||c1!=cZ){cX=c5;cZ=c1;b0(cY,a,c1);if(c1){c5=c1}if(c3){cY.html(c2.get())}else{if(c4){cY.html("");cY.append(c5)}else{cY.text(c5===cS?"":c5)}}}},cY)}});var bD={};function cT(cW){var cV=bD[cW];if(!cV){var cX=[];aS(aZ(cW),function(cZ){var cY=cI(cZ);cX.push(cY?function(c1){var c0,c2=this.$tryEval(cY,function(c3){c0=cm(c3)});b0(c1,a,c0);return c0?c0:c2}:function(){return cZ})});bD[cW]=cV=function(c1){var c3=[],cY=this,cZ=this.hasOwnProperty(by)?cY.$element:cS;cY.$element=c1;for(var c0=0;c0<cX.length;c0++){var c2=cX[c0].call(cY,c1);if(bJ(c2)){c2=""}else{if(cR(c2)){c2=cm(c2,true)}}c3.push(c2)}cY.$element=cZ;return c3.join("")}}return cV}Z("ng:bind-template",function(cW,cV){cV.addClass("ng-binding");var cX=cT(cW);return function(cZ){var cY;this.$onEval(function(){var c0=cX.call(this,cZ);if(c0!=cY){cZ.text(c0);cY=c0}},cZ)}});var f={disabled:"disabled",readonly:"readOnly",checked:"checked",selected:"selected"};Z("ng:bind-attr",function(cV){return function(cY){var cX={};var cW=cY.data(ac)||j;this.$onEval(function(){var cZ=this.$eval(cV),c1=j;for(var c0 in cZ){var c3=cT(cZ[c0]).call(this,cY),c2=f[am(c0)];if(cX[c0]!==c3){cX[c0]=c3;if(c2){if(cp(c3)){cY.attr(c2,c2);cY.attr("ng-"+c2,c3)}else{cY.removeAttr(c2);cY.removeAttr("ng-"+c2)}(cY.data(bf)||j)()}else{cY.attr(c0,c3)}c1=cW}}c1()},cY)}});Z("ng:click",function(cW,cV){return function(cY){var cX=this;cY.bind("click",function(cZ){cX.$tryEval(cW,cY);cX.$root.$eval();cZ.stopPropagation()})}});Z("ng:submit",function(cW,cV){return function(cY){var cX=this;cY.bind("submit",function(cZ){cX.$tryEval(cW,cY);cX.$root.$eval();cZ.preventDefault()})}});Z("ng:watch",function(cW,cV){return function(cY){var cX=this;S(cW).watch()({addListener:function(cZ,c0){cX.$watch(cZ,function(){return c0(cX)},cY)}})}});function bE(cV){return function(cY,cW){var cX=cW[0].className+" ";return function(cZ){this.$onEval(function(){if(cV(this.$index)){var c0=this.$eval(cY);if(a9(c0)){c0=c0.join(" ")}cZ[0].className=av(cX+c0)}},cZ)}}}Z("ng:class",bE(function(){return true}));Z("ng:class-odd",bE(function(cV){return cV%2===0}));Z("ng:class-even",bE(function(cV){return cV%2===1}));Z("ng:show",function(cW,cV){return function(cX){this.$onEval(function(){cX.css(aL,cp(this.$eval(cW))?"":b)},cX)}});Z("ng:hide",function(cW,cV){return function(cX){this.$onEval(function(){cX.css(aL,cp(this.$eval(cW))?b:"")},cX)}});Z("ng:style",function(cW,cV){return function(cX){var cY=cb(cX);this.$onEval(function(){var c0=this.$eval(cW)||{},cZ,c1={};for(cZ in c0){if(cY[cZ]===cS){cY[cZ]=""}c1[cZ]=c0[cZ]}for(cZ in cY){c1[cZ]=c1[cZ]||cY[cZ]}cX.css(c1)},cX)}});function aZ(cW){var cX=[];var cY=0;var cV;while((cV=cW.indexOf("{{",cY))>-1){if(cY<cV){cX.push(cW.substr(cY,cV-cY))}cY=cV;cV=cW.indexOf("}}",cV);cV=cV<0?cW.length:cV+2;cX.push(cW.substr(cY,cV-cY));cY=cV}if(cY!=cW.length){cX.push(cW.substr(cY,cW.length-cY))}return cX.length===0?[cW]:cX}function cI(cV){var cW=cV.replace(/\n/gm," ").match(/^\{\{(.*)\}\}$/);return cW?cW[1]:a6}function cH(cV){return cV.length>1||cI(cV[0])!==a6}ag("{{}}",function(cZ,cY,cV){var c1=aZ(cZ),cW=this;if(cH(c1)){if(b4(cV[0])){cV.attr("ng:bind-template",cZ)}else{var cX=cY,c0;aS(aZ(cZ),function(c4){var c3=cI(c4);if(c3){c0=cW.element("span");c0.attr("ng:bind",c3)}else{c0=cW.text(c4)}if(at&&c4.charAt(0)==" "){c0=ck("<span> </span>");var c2=c0.html();c0.text(c4.substr(1));c0.html(c2+c0.html())}cX.after(c0);cX=c0});cY.remove()}}});ag("OPTION",function(cY,cX,cW){if(au(cW)=="OPTION"){var cV=r.createElement("select");cV.insertBefore(cW[0].cloneNode(true),a6);if(!cV.innerHTML.match(/<option(\s.*\s|\s)value\s*=\s*.*>.*<\/\s*option\s*>/gi)){cW.attr("value",cY)}}});var bL="ng:bind-attr";var aH={"ng:src":"src","ng:href":"href"};s("{{}}",function(cY,cW,cX){if(Z(cW)||Z("@"+cW)){return}if(at&&cW=="src"){cY=decodeURI(cY)}var cZ=aZ(cY),cV;if(cH(cZ)){cX.removeAttr(cW);cV=Q(cX.attr(bL)||"{}");cV[aH[cW]||cW]=cY;cX.attr(bL,cm(cV))}});function bN(cW,cV){var cX=cV.attr("name");if(!cX){throw"Required field 'name' not found."}return{get:function(){return cW.$eval(cX)},set:function(cY){if(cY!==cS){return cW.$tryEval(cX+"="+cm(cY),cV)}}}}function bn(cY,cX){var cV=bN(cY,cX),cZ=cX.attr("ng:format")||o,cW=l(cZ);if(!cW){throw"Formatter named '"+cZ+"' not found."}return{get:function(){return cW.format(cV.get())},set:function(c0){return cV.set(cW.parse(c0))}}}function d(cV){return S(cV).validator()()}function b1(c6,cZ){var cX=cZ.attr("ng:validate")||o,cW=d(cX),cV=cZ.attr("ng:required"),c7=cZ.attr("ng:format")||o,c5=l(c7),c4,cY,c1,c0,c3=c6.$invalidWidgets||{markValid:j,markInvalid:j};if(!cW){throw"Validator named '"+cX+"' not found."}if(!c5){throw"Formatter named '"+c7+"' not found."}c4=c5.format;cY=c5.parse;if(cV){c6.$watch(cV,function(c8){c0=c8;c2()})}else{c0=cV===""}cZ.data(bf,c2);return{get:function(){if(c1){b0(cZ,k,a6)}try{var c8=cY(cZ.val());c2();return c8}catch(c9){c1=c9;b0(cZ,k,c9)}},set:function(c9){var c8=cZ.val(),da=c4(c9);if(c8!=da){cZ.val(da||"")}c2()}};function c2(){var da=av(cZ.val());if(cZ[0].disabled||cZ[0].readOnly){b0(cZ,k,a6);c3.markValid(cZ)}else{var c9,c8=b5(c6,{$element:cZ});c9=c0&&!da?"Required":(da?cW(c8,da):a6);b0(cZ,k,c9);c1=c9;if(c9){c3.markInvalid(cZ)}else{c3.markValid(cZ)}}}}function aJ(cW,cV){var cY=cV[0],cX=cY.value;return{get:function(){return !!cY.checked},set:function(cZ){cY.checked=cp(cZ)}}}function cP(cW,cV){var cX=cV[0];return{get:function(){return cX.checked?cX.value:a6},set:function(cY){cX.checked=cY==cX.value}}}function cz(cX,cW){var cV=cW[0].options;return{get:function(){var cY=[];aS(cV,function(cZ){if(cZ.selected){cY.push(cZ.value)}});return cY},set:function(cY){var cZ={};aS(cY,function(c0){cZ[c0]=true});aS(cV,function(c0){c0.selected=cZ[c0.value]})}}}function O(){return{get:j,set:j}}var bl=bZ("keyup change",bN,b1,h()),b3=bZ("click",O,O,j),cM={text:bl,textarea:bl,hidden:bl,password:bl,button:b3,submit:b3,reset:b3,image:b3,checkbox:bZ("click",bn,aJ,h(false)),radio:bZ("click",bn,cP,ct),"select-one":bZ("change",bn,b1,h(a6)),"select-multiple":bZ("change",bn,cz,h([]))};function h(cV){return function(cX,cW){var cY=cW.get();if(!cY&&cv(cV)){cY=bv(cV)}if(bB(cX.get())&&cv(cY)){cX.set(cY)}}}function ct(cY,cV,cZ){var cX=cY.get(),c0=cV.get(),cW=cZ[0];cW.checked=false;cW.name=this.$id+"@"+cW.name;if(bB(cX)){cY.set(cX=a6)}if(cX==a6&&c0!==a6){cY.set(c0)}cV.set(cX)}function bZ(cX,cW,cV,cY){return function(c2){var c3=this,c1=cW(c3,c2),cZ=cV(c3,c2),c4=c2.attr("ng:change")||"",c0;cY.call(c3,c1,cZ,c2);this.$eval(c2.attr("ng:init")||"");if(c4||cW!==O){c2.bind(cX,function(){c1.set(cZ.get());c0=c1.get();c3.$tryEval(c4,c2);c3.$root.$eval()})}c3.$watch(c1.get,function(c5){if(c0!==c5){cZ.set(c0=c5)}})}}function X(cV){this.directives(true);return cM[am(cV[0].type)]||j}B("input",X);B("textarea",X);B("button",X);B("select",function(cV){this.descend(true);return X.call(this,cV)});B("option",function(){this.descend(true);this.directives(true);return function(cZ){var cV=cZ.parent();var c1=ae(cV);var cY=bn(c1,cV);var cW=b1(c1,cV);var c0=cZ;var cX=c0.attr(ay);var c2=c0.attr("ng-"+aA);cZ.data(ac,function(){var c5=c0.attr(ay);var c4=c0.attr("ng-"+aA);var c3=cY.get();if(c2!=c4||cX!=c5){c2=c4;cX=c5;if(c4||c3==a6||c3==cS){cY.set(c5)}if(c5==c3){cW.set(cX)}}})}});B("ng:include",function(cX){var cY=this,cW=cX.attr("src"),cZ=cX.attr("scope")||"",cV=cX[0].getAttribute("onload")||"";if(cX[0]["ng:compiled"]){this.descend(true);this.directives(true)}else{cX[0]["ng:compiled"]=true;return b7(function(c5,c2){var c4=this,c0;var c6=0;var c3=false;function c1(){c6++}this.$watch(cW,c1);this.$watch(cZ,c1);c4.$onEval(function(){if(c0&&!c3){c3=true;try{c0.$eval()}finally{c3=false}}});this.$watch(function(){return c6},function(){var c8=this.$eval(cW),c7=this.$eval(cZ);if(c8){c5("GET",c8,function(da,c9){c2.html(c9);c0=c7||bV(c4);cY.compile(c2)(c2,c0);c0.$init();c4.$eval(cV)})}else{c0=null;c2.html("")}})},{$inject:["$xhr.cache"]})}});var m=B("ng:switch",function(cZ){var c0=this,cY=cZ.attr("on"),c2=(cZ.attr("using")||"equals"),cV=c2.split(":"),cW=m[cV.shift()],cX=cZ.attr("change")||"",c1=[];if(!cW){throw"Using expression '"+c2+"' unknown."}if(!cY){throw"Missing 'on' attribute."}aX(cZ,function(c5){var c3=c5.attr("ng:switch-when");var c4={change:cX,element:c5,template:c0.compile(c5)};if(ci(c3)){c4.when=function(c7,c8){var c6=[c8,c3];aS(cV,function(c9){c6.push(c9)});return cW.apply(c7,c6)};c1.unshift(c4)}else{if(ci(c5.attr("ng:switch-default"))){c4.when=cr(true);c1.push(c4)}}});aS(c1,function(c3){c3.element.remove()});cZ.html("");return function(c4){var c5=this,c3;this.$watch(cY,function(c7){var c6=false;c4.html("");c3=bV(c5);aS(c1,function(c8){if(!c6&&c8.when(c3,c7)){c6=true;var c9=A(c8.element);c4.append(c9);c3.$tryEval(c8.change,c4);c8.template(c9,c3);c3.$init()}})});c5.$onEval(function(){if(c3){c3.$eval()}})}},{equals:function(cW,cV){return""+cW==cV},route:bj});B("a",function(){this.descend(true);this.directives(true);return function(cV){if(cV.attr("href")===""){cV.bind("click",function(cW){cW.preventDefault()})}}});B("@ng:repeat",function(cX,cV){cV.removeAttr("ng:repeat");cV.replaceWith(this.comment("ng:repeat: "+cX));var cW=this.compile(cV);return function(cY){var c2=cX.match(/^\s*(.+)\s+in\s+(.*)\s*$/),cZ,c5,c0,c4;if(!c2){throw cK("Expected ng:repeat in form of 'item in collection' but got '"+cX+"'.")}cZ=c2[1];c5=c2[2];c2=cZ.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/);if(!c2){throw cK("'item' in 'item in collection' should be identifier or (key, value) but got '"+keyValue+"'.")}c0=c2[3]||c2[1];c4=c2[2];var c3=[],c1=this;this.$onEval(function(){var c8=0,c7=c3.length,dd=cY,dc=this.$tryEval(c5,cY),da=a9(dc),db=0,c6,c9;if(da){db=dc.length}else{for(c9 in dc){if(dc.hasOwnProperty(c9)){db++}}}for(c9 in dc){if(!da||dc.hasOwnProperty(c9)){if(c8<c7){c6=c3[c8];c6[c0]=dc[c9];if(c4){c6[c4]=c9}}else{c6=cW(A(cV),bV(c1));c6[c0]=dc[c9];if(c4){c6[c4]=c9}dd.after(c6.$element);c6.$index=c8;c6.$position=c8==0?"first":(c8==db-1?"last":"middle");c6.$element.attr("ng:repeat-index",c8);c6.$init();c3.push(c6)}c6.$eval();dd=c6.$element;c8++}}while(c3.length>c8){c3.pop().$element.remove()}},cY)}});B("@ng:non-bindable",j);var cj;bs("$browser",function(cV){if(!cj){cj=new aO(bU.location,ck(bU.document),ck(bU.document.getElementsByTagName("head")[0]),L,cV,bU.setTimeout);cj.startPoller(50,function(cW,cX){setTimeout(cW,cX)});cj.bind()}return cj},{inject:["$log"]});b7(aB,{element:ck,compile:a2,scope:bV,copy:bv,extend:b7,equals:p,foreach:aS,injector:bY,noop:j,bind:bF,toJson:cm,fromJson:Q,identity:aG,isUndefined:bB,isDefined:cv,isString:ci,isFunction:E,isObject:cR,isNumber:aU,isArray:a9});aB.scenario=aB.scenario||{};aB.scenario.output=aB.scenario.output||function(cV,cW){aB.scenario.output[cV]=cW};aB.scenario.dsl=aB.scenario.dsl||function(cV,cW){aB.scenario.dsl[cV]=function(){function cX(c3,c1){var cZ=c3.apply(this,c1);if(aB.isFunction(cZ)||cZ instanceof aB.scenario.Future){return cZ}var c0=this;var c2=aB.extend({},cZ);aB.foreach(c2,function(c5,c4){if(aB.isFunction(c5)){c2[c4]=function(){return cX.call(c0,c5,arguments)}}else{c2[c4]=c5}});return c2}var cY=cW.apply(this,arguments);return function(){return cX.call(this,cY,arguments)}}};aB.scenario.matcher=aB.scenario.matcher||function(cV,cW){aB.scenario.matcher[cV]=function(cY){var cZ="expect "+this.future.name+" ";if(this.inverse){cZ+="not "}var cX=this;this.addFuture(cZ+cV+" "+aB.toJson(cY),function(c0){var c1;cX.actual=cX.future.value;if((cX.inverse&&cW.call(cX,cY))||(!cX.inverse&&!cW.call(cX,cY))){c1="expected "+aB.toJson(cY)+" but was "+aB.toJson(cX.actual)}c0(c1)})}};function i(c0,cZ){var cX=bU.location.href;var cV=b8(r.body);var cW=[];if(cZ.scenario_output){cW=cZ.scenario_output.split(",")}aB.foreach(aB.scenario.output,function(c4,c2){if(!cW.length||cO(cW,c2)!=-1){var c3=cV.append("<div></div>").find("div:last");c3.attr("id",c2);c4.call({},c3,c0)}});if(!/^http/.test(cX)&&!/^https/.test(cX)){cV.append('<p id="system-error"></p>');cV.find("#system-error").text("Scenario runner must be run using http or https. The protocol "+cX.split(":")[0]+":// is not supported.");return}var c1=cV.append('<div id="application"></div>').find("#application");var cY=new aB.scenario.Application(c1);c0.on("RunnerEnd",function(){c1.css("display","none");c1.find("iframe").attr("src","about:blank")});c0.on("RunnerError",function(c2){if(bU.console){console.log(V(c2))}else{alert(c2)}});c0.run(cY)}function W(cZ,cY,cW){var cX=0;function cV(c1,c0){if(c0&&c0>cX){cX=c0}if(c1||cX>=cZ.length){cW(c1)}else{try{cY(cZ[cX++],cV)}catch(c2){cW(c2)}}}cV()}function V(cW,cX){cX=cX||5;var cY=cW.toString();if(cW.stack){var cV=cW.stack.split("\n");if(cV[0].indexOf(cY)===-1){cX++;cV.unshift(cW.message)}cY=cV.slice(0,cX).join("\n")}return cY}function x(cW){var cV=new cK();return function(){var cX=(cV.stack||"").split("\n")[cW];if(cX){if(cX.indexOf("@")!==-1){cX=cX.substring(cX.indexOf("@")+1)}else{cX=cX.substring(cX.indexOf("(")+1).replace(")","")}}return cX||""}}function c(cV,cW){if(cV&&!cV.nodeName){cV=cV[0]}if(!cV){return}if(!cW){cW={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"}[cV.type]||"click"}if(am(au(cV))=="option"){cV.parentNode.value=cV.value;cV=cV.parentNode;cW="change"}if(at){switch(cV.type){case"radio":case"checkbox":cV.checked=!cV.checked;break}cV.fireEvent("on"+cW);if(am(cV.type)=="submit"){while(cV){if(am(cV.nodeName)=="form"){cV.fireEvent("onsubmit");break}cV=cV.parentNode}}}else{var cX=r.createEvent("MouseEvents");cX.initMouseEvent(cW,true,true,bU,0,0,0,0,0,false,false,false,false,0,cV);cV.dispatchEvent(cX)}}(function(cW){var cV=cW.trigger;cW.trigger=function(cX){if(/(click|change|keyup)/.test(cX)){return this.each(function(cY,cZ){c(cZ,cX)})}return cV.apply(this,arguments)}})(b8.fn);b8.fn.bindings=function(cW){function cX(cZ,cY){return cY instanceof RegExp?cY.test(cZ):cZ&&cZ.indexOf(cY)>=0}var cV=[];this.find(".ng-binding:visible").each(function(){var cY=new b8(this);if(!aB.isDefined(cW)||cX(cY.attr("ng:bind"),cW)||cX(cY.attr("ng:bind-template"),cW)){if(cY.is("input, textarea")){cV.push(cY.val())}else{cV.push(cY.html())}}});return cV};aB.scenario.Application=function(cV){this.context=cV;cV.append('<h2>Current URL: <a href="about:blank">None</a></h2><div id="test-frames"></div>')};aB.scenario.Application.prototype.getFrame_=function(){return this.context.find("#test-frames iframe:last")};aB.scenario.Application.prototype.getWindow_=function(){var cV=this.getFrame_().attr("contentWindow");if(!cV){throw"Frame window is not accessible."}return cV};aB.scenario.Application.prototype.checkUrlStatus_=function(cW,cX){var cV=this;b8.ajax({url:cW,type:"HEAD",complete:function(cY){if(cY.status<200||cY.status>=300){if(!cY.status){cX.call(cV,"Sandbox Error: Cannot access "+cW)}else{cX.call(cV,cY.status+" "+cY.statusText)}}else{cX.call(cV)}}})};aB.scenario.Application.prototype.navigateTo=function(cW,cX,cZ){var cV=this;var cY=this.getFrame_();cZ=cZ||function(c0){throw c0};if(cW==="about:blank"){cZ("Sandbox Error: Navigating to about:blank is not allowed.")}else{if(cW.charAt(0)==="#"){cW=cY.attr("src").split("#")[0]+cW;cY.attr("src",cW);this.executeAction(cX)}else{cY.css("display","none").attr("src","about:blank");this.checkUrlStatus_(cW,function(c0){if(c0){return cZ(c0)}cV.context.find("#test-frames").append("<iframe>");cY=this.getFrame_();cY.load(function(){cY.unbind();try{cV.executeAction(cX)}catch(c1){cZ(c1)}}).attr("src",cW)})}}this.context.find("> h2 a").attr("href",cW).text(cW)};aB.scenario.Application.prototype.executeAction=function(cX){var cW=this;var cY=this.getWindow_();if(!cY.document){throw"Sandbox Error: Application document not accessible."}if(!cY.angular){return cX.call(this,cY,b8(cY.document))}var cV=cY.angular.service.$browser();cV.poll();cV.notifyWhenNoOutstandingRequests(function(){cX.call(cW,cY,b8(cY.document))})};aB.scenario.Describe=function(cW,cY){this.only=cY&&cY.only;this.beforeEachFns=[];this.afterEachFns=[];this.its=[];this.children=[];this.name=cW;this.parent=cY;this.id=aB.scenario.Describe.id++;var cV=this.beforeEachFns;this.setupBefore=function(){if(cY){cY.setupBefore.call(this)}aB.foreach(cV,function(cZ){cZ.call(this)},this)};var cX=this.afterEachFns;this.setupAfter=function(){aB.foreach(cX,function(cZ){cZ.call(this)},this);if(cY){cY.setupAfter.call(this)}}};aB.scenario.Describe.id=0;aB.scenario.Describe.prototype.beforeEach=function(cV){this.beforeEachFns.push(cV)};aB.scenario.Describe.prototype.afterEach=function(cV){this.afterEachFns.push(cV)};aB.scenario.Describe.prototype.describe=function(cW,cV){var cX=new aB.scenario.Describe(cW,this);this.children.push(cX);cV.call(cX)};aB.scenario.Describe.prototype.ddescribe=function(cW,cV){var cX=new aB.scenario.Describe(cW,this);cX.only=true;this.children.push(cX);cV.call(cX)};aB.scenario.Describe.prototype.xdescribe=aB.noop;aB.scenario.Describe.prototype.it=function(cW,cV){this.its.push({definition:this,only:this.only,name:cW,before:this.setupBefore,body:cV,after:this.setupAfter})};aB.scenario.Describe.prototype.iit=function(cW,cV){this.it.apply(this,arguments);this.its[this.its.length-1].only=true};aB.scenario.Describe.prototype.xit=aB.noop;aB.scenario.Describe.prototype.getSpecs=function(){var cW=arguments[0]||[];aB.foreach(this.children,function(cX){cX.getSpecs(cW)});aB.foreach(this.its,function(cX){cW.push(cX)});var cV=[];aB.foreach(cW,function(cX){if(cX.only){cV.push(cX)}});return(cV.length&&cV)||cW};aB.scenario.Future=function(cW,cX,cV){this.name=cW;this.behavior=cX;this.fulfilled=false;this.value=undefined;this.parser=aB.identity;this.line=cV||function(){return""}};aB.scenario.Future.prototype.execute=function(cW){var cV=this;this.behavior(function(cY,cX){cV.fulfilled=true;if(cX){try{cX=cV.parser(cX)}catch(cZ){cY=cZ}}cV.value=cY||cX;cW(cY,cX)})};aB.scenario.Future.prototype.parsedWith=function(cV){this.parser=cV;return this};aB.scenario.Future.prototype.fromJson=function(){return this.parsedWith(aB.fromJson)};aB.scenario.Future.prototype.toJson=function(){return this.parsedWith(aB.toJson)};aB.scenario.ObjectModel=function(cX){var cW=this;this.specMap={};this.value={name:"",children:{}};cX.on("SpecBegin",function(cY){var cZ=cW.value;aB.foreach(cW.getDefinitionPath(cY),function(c0){if(!cZ.children[c0.name]){cZ.children[c0.name]={id:c0.id,name:c0.name,children:{},specs:{}}}cZ=cZ.children[c0.name]});cW.specMap[cY.id]=cZ.specs[cY.name]=new aB.scenario.ObjectModel.Spec(cY.id,cY.name)});cX.on("SpecError",function(cY,cZ){var c0=cW.getSpec(cY.id);c0.status="error";c0.error=cZ});cX.on("SpecEnd",function(cY){var cZ=cW.getSpec(cY.id);cV(cZ)});cX.on("StepBegin",function(cY,c0){var cZ=cW.getSpec(cY.id);cZ.steps.push(new aB.scenario.ObjectModel.Step(c0.name))});cX.on("StepEnd",function(cY,c0){var cZ=cW.getSpec(cY.id);if(cZ.getLastStep().name!==c0.name){throw"Events fired in the wrong order. Step names don' match."}cV(cZ.getLastStep())});cX.on("StepFailure",function(cY,c2,cZ){var c0=cW.getSpec(cY.id);var c1=c0.getLastStep();c1.error=cZ;if(!c0.status){c0.status=c1.status="failure"}});cX.on("StepError",function(cY,c2,cZ){var c0=cW.getSpec(cY.id);var c1=c0.getLastStep();c0.status="error";c1.status="error";c1.error=cZ});function cV(cY){cY.endTime=new Date().getTime();cY.duration=cY.endTime-cY.startTime;cY.status=cY.status||"success"}};aB.scenario.ObjectModel.prototype.getDefinitionPath=function(cV){var cX=[];var cW=cV.definition;while(cW&&cW.name){cX.unshift(cW);cW=cW.parent}return cX};aB.scenario.ObjectModel.prototype.getSpec=function(cV){return this.specMap[cV]};aB.scenario.ObjectModel.Spec=function(cW,cV){this.id=cW;this.name=cV;this.startTime=new Date().getTime();this.steps=[]};aB.scenario.ObjectModel.Spec.prototype.addStep=function(cV){var cW=new aB.scenario.ObjectModel.Step(cV);this.steps.push(cW);return cW};aB.scenario.ObjectModel.Spec.prototype.getLastStep=function(){return this.steps[this.steps.length-1]};aB.scenario.ObjectModel.Step=function(cV){this.name=cV;this.startTime=new Date().getTime()};aB.scenario.Describe=function(cW,cY){this.only=cY&&cY.only;this.beforeEachFns=[];this.afterEachFns=[];this.its=[];this.children=[];this.name=cW;this.parent=cY;this.id=aB.scenario.Describe.id++;var cV=this.beforeEachFns;this.setupBefore=function(){if(cY){cY.setupBefore.call(this)}aB.foreach(cV,function(cZ){cZ.call(this)},this)};var cX=this.afterEachFns;this.setupAfter=function(){aB.foreach(cX,function(cZ){cZ.call(this)},this);if(cY){cY.setupAfter.call(this)}}};aB.scenario.Describe.id=0;aB.scenario.Describe.prototype.beforeEach=function(cV){this.beforeEachFns.push(cV)};aB.scenario.Describe.prototype.afterEach=function(cV){this.afterEachFns.push(cV)};aB.scenario.Describe.prototype.describe=function(cW,cV){var cX=new aB.scenario.Describe(cW,this);this.children.push(cX);cV.call(cX)};aB.scenario.Describe.prototype.ddescribe=function(cW,cV){var cX=new aB.scenario.Describe(cW,this);cX.only=true;this.children.push(cX);cV.call(cX)};aB.scenario.Describe.prototype.xdescribe=aB.noop;aB.scenario.Describe.prototype.it=function(cW,cV){this.its.push({definition:this,only:this.only,name:cW,before:this.setupBefore,body:cV,after:this.setupAfter})};aB.scenario.Describe.prototype.iit=function(cW,cV){this.it.apply(this,arguments);this.its[this.its.length-1].only=true};aB.scenario.Describe.prototype.xit=aB.noop;aB.scenario.Describe.prototype.getSpecs=function(){var cW=arguments[0]||[];aB.foreach(this.children,function(cX){cX.getSpecs(cW)});aB.foreach(this.its,function(cX){cW.push(cX)});var cV=[];aB.foreach(cW,function(cX){if(cX.only){cV.push(cX)}});return(cV.length&&cV)||cW};aB.scenario.Runner=function(cV){this.listeners=[];this.$window=cV;this.rootDescribe=new aB.scenario.Describe();this.currentDescribe=this.rootDescribe;this.api={it:this.it,iit:this.iit,xit:aB.noop,describe:this.describe,ddescribe:this.ddescribe,xdescribe:aB.noop,beforeEach:this.beforeEach,afterEach:this.afterEach};aB.foreach(this.api,aB.bind(this,function(cX,cW){this.$window[cW]=aB.bind(this,cX)}))};aB.scenario.Runner.prototype.emit=function(cW){var cV=this;var cX=Array.prototype.slice.call(arguments,1);cW=cW.toLowerCase();if(!this.listeners[cW]){return}aB.foreach(this.listeners[cW],function(cY){cY.apply(cV,cX)})};aB.scenario.Runner.prototype.on=function(cV,cW){cV=cV.toLowerCase();this.listeners[cV]=this.listeners[cV]||[];this.listeners[cV].push(cW)};aB.scenario.Runner.prototype.describe=function(cX,cV){var cW=this;this.currentDescribe.describe(cX,function(){var cY=cW.currentDescribe;cW.currentDescribe=this;try{cV.call(this)}finally{cW.currentDescribe=cY}})};aB.scenario.Runner.prototype.ddescribe=function(cX,cV){var cW=this;this.currentDescribe.ddescribe(cX,function(){var cY=cW.currentDescribe;cW.currentDescribe=this;try{cV.call(this)}finally{cW.currentDescribe=cY}})};aB.scenario.Runner.prototype.it=function(cW,cV){this.currentDescribe.it(cW,cV)};aB.scenario.Runner.prototype.iit=function(cW,cV){this.currentDescribe.iit(cW,cV)};aB.scenario.Runner.prototype.beforeEach=function(cV){this.currentDescribe.beforeEach(cV)};aB.scenario.Runner.prototype.afterEach=function(cV){this.currentDescribe.afterEach(cV)};aB.scenario.Runner.prototype.createSpecRunner_=function(cV){return cV.$new(aB.scenario.SpecRunner)};aB.scenario.Runner.prototype.run=function(cW){var cV=this;var cX=aB.scope(this);cX.application=cW;this.emit("RunnerBegin");W(this.rootDescribe.getSpecs(),function(cY,c1){var cZ={};var c0=cV.createSpecRunner_(cX);aB.foreach(aB.scenario.dsl,function(c3,c2){cZ[c2]=c3.call(cX)});aB.foreach(aB.scenario.dsl,function(c3,c2){cV.$window[c2]=function(){var c4=x(3);var c5=aB.scope(c0);c5.dsl={};aB.foreach(cZ,function(c7,c6){c5.dsl[c6]=function(){return cZ[c6].apply(c5,arguments)}});c5.addFuture=function(){Array.prototype.push.call(arguments,c4);return aB.scenario.SpecRunner.prototype.addFuture.apply(c5,arguments)};c5.addFutureAction=function(){Array.prototype.push.call(arguments,c4);return aB.scenario.SpecRunner.prototype.addFutureAction.apply(c5,arguments)};return c5.dsl[c2].apply(c5,arguments)}});c0.run(cY,c1)},function(cY){if(cY){cV.emit("RunnerError",cY)}cV.emit("RunnerEnd")})};aB.scenario.SpecRunner=function(){this.futures=[];this.afterIndex=0};aB.scenario.SpecRunner.prototype.run=function(cW,cY){var cV=this;this.spec=cW;this.emit("SpecBegin",cW);try{cW.before.call(this);cW.body.call(this);this.afterIndex=this.futures.length;cW.after.call(this)}catch(cX){this.emit("SpecError",cW,cX);this.emit("SpecEnd",cW);cY();return}var cZ=function(c1,c0){if(cV.error){return c0()}cV.error=true;c0(null,cV.afterIndex)};W(this.futures,function(c0,c1){cV.step=c0;cV.emit("StepBegin",cW,c0);try{c0.execute(function(c3){if(c3){cV.emit("StepFailure",cW,c0,c3);cV.emit("StepEnd",cW,c0);return cZ(c3,c1)}cV.emit("StepEnd",cW,c0);cV.$window.setTimeout(function(){c1()},0)})}catch(c2){cV.emit("StepError",cW,c0,c2);cV.emit("StepEnd",cW,c0);cZ(c2,c1)}},function(c0){if(c0){cV.emit("SpecError",cW,c0)}cV.emit("SpecEnd",cW);cV.$window.setTimeout(function(){cY()},0)})};aB.scenario.SpecRunner.prototype.addFuture=function(cX,cY,cW){var cV=new aB.scenario.Future(cX,aB.bind(this,cY),cW);this.futures.push(cV);return cV};aB.scenario.SpecRunner.prototype.addFutureAction=function(cX,cY,cV){var cW=this;return this.addFuture(cX,function(cZ){this.application.executeAction(function(c2,c1){c1.elements=function(c4){var c5=Array.prototype.slice.call(arguments,1);c4=(cW.selector||"")+" "+(c4||"");c4=b8.trim(c4)||"*";aB.foreach(c5,function(c7,c6){c4=c4.replace("$"+(c6+1),c7)});var c3=c1.find(c4);if(!c3.length){throw {type:"selector",message:"Selector "+c4+" did not match any elements."}}return c3};try{cY.call(cW,c2,c1,cZ)}catch(c0){if(c0.type&&c0.type==="selector"){cZ(c0.message)}else{throw c0}}})},cV)};aB.scenario.dsl("wait",function(){return function(){return this.addFuture("waiting for you to resume",function(cV){this.emit("InteractiveWait",this.spec,this.step);this.$window.resume=function(){cV()}})}});aB.scenario.dsl("pause",function(){return function(cV){return this.addFuture("pause for "+cV+" seconds",function(cW){this.$window.setTimeout(function(){cW(null,cV*1000)},cV*1000)})}});aB.scenario.dsl("browser",function(){var cV={};cV.navigateTo=function(cX,cY){var cW=this.application;return this.addFuture("browser navigate to '"+cX+"'",function(cZ){if(cY){cX=cY.call(this,cX)}cW.navigateTo(cX,function(){cZ(null,cX)},cZ)})};cV.reload=function(){var cW=this.application;return this.addFutureAction("browser reload",function(c0,cZ,cX){var cY=c0.location.href;cW.navigateTo(cY,function(){cX(null,cY)},cX)})};cV.location=function(){var cW={};cW.href=function(){return this.addFutureAction("browser url",function(cZ,cY,cX){cX(null,cZ.location.href)})};cW.hash=function(){return this.addFutureAction("browser url hash",function(cZ,cY,cX){cX(null,cZ.location.hash.replace("#",""))})};cW.path=function(){return this.addFutureAction("browser url path",function(cZ,cY,cX){cX(null,cZ.location.pathname)})};cW.search=function(){return this.addFutureAction("browser url search",function(cZ,cY,cX){cX(null,cZ.angular.scope().$location.search)})};cW.hashSearch=function(){return this.addFutureAction("browser url hash search",function(cZ,cY,cX){cX(null,cZ.angular.scope().$location.hashSearch)})};cW.hashPath=function(){return this.addFutureAction("browser url hash path",function(cZ,cY,cX){cX(null,cZ.angular.scope().$location.hashPath)})};return cW};return function(cW){return cV}});aB.scenario.dsl("expect",function(){var cV=aB.extend({},aB.scenario.matcher);cV.not=function(){this.inverse=true;return cV};return function(cW){this.future=cW;return cV}});aB.scenario.dsl("using",function(){return function(cV,cW){this.selector=b8.trim((this.selector||"")+" "+cV);if(aB.isString(cW)&&cW.length){this.label=cW+" ( "+this.selector+" )"}else{this.label=this.selector}return this.dsl}});aB.scenario.dsl("binding",function(){return function(cV){return this.addFutureAction("select binding '"+cV+"'",function(cZ,cY,cW){var cX=cY.elements().bindings(cV);if(!cX.length){return cW("Binding selector '"+cV+"' did not match.")}cW(null,cX[0])})}});aB.scenario.dsl("input",function(){var cV={};cV.enter=function(cW){return this.addFutureAction("input '"+this.name+"' enter '"+cW+"'",function(c0,cZ,cX){var cY=cZ.elements(':input[name="$1"]',this.name);cY.val(cW);cY.trigger("change");cX()})};cV.check=function(){return this.addFutureAction("checkbox '"+this.name+"' toggle",function(cZ,cY,cW){var cX=cY.elements(':checkbox[name="$1"]',this.name);cX.trigger("click");cW()})};cV.select=function(cW){return this.addFutureAction("radio button '"+this.name+"' toggle '"+cW+"'",function(c0,cZ,cX){var cY=cZ.elements(':radio[name$="@$1"][value="$2"]',this.name,cW);cY.trigger("click");cX()})};return function(cW){this.name=cW;return cV}});aB.scenario.dsl("repeater",function(){var cV={};cV.count=function(){return this.addFutureAction("repeater '"+this.label+"' count",function(cZ,cY,cW){try{cW(null,cY.elements().length)}catch(cX){cW(null,0)}})};cV.column=function(cW){return this.addFutureAction("repeater '"+this.label+"' column '"+cW+"'",function(cZ,cY,cX){cX(null,cY.elements().bindings(cW))})};cV.row=function(cW){return this.addFutureAction("repeater '"+this.label+"' row '"+cW+"'",function(c1,c0,cX){var cY=[];var cZ=c0.elements().slice(cW,cW+1);if(!cZ.length){return cX("row "+cW+" out of bounds")}cX(null,cZ.bindings())})};return function(cW,cX){this.dsl.using(cW,cX);return cV}});aB.scenario.dsl("select",function(){var cV={};cV.option=function(cW){return this.addFutureAction("select '"+this.name+"' option '"+cW+"'",function(c0,cZ,cY){var cX=cZ.elements('select[name="$1"]',this.name);cX.val(cW);cX.trigger("change");cY()})};cV.options=function(){var cW=arguments;return this.addFutureAction("select '"+this.name+"' options '"+cW+"'",function(c0,cZ,cY){var cX=cZ.elements('select[multiple][name="$1"]',this.name);cX.val(cW);cX.trigger("change");cY()})};return function(cW){this.name=cW;return cV}});aB.scenario.dsl("element",function(){var cV=["attr","css"];var cX=["val","text","html","height","innerHeight","outerHeight","width","innerWidth","outerWidth","position","scrollLeft","scrollTop","offset"];var cW={};cW.count=function(){return this.addFutureAction("element '"+this.label+"' count",function(c1,c0,cY){try{cY(null,c0.elements().length)}catch(cZ){cY(null,0)}})};cW.click=function(){return this.addFutureAction("element '"+this.label+"' click",function(c2,c1,cY){var c0=c1.elements();var cZ=c0.attr("href");c0.trigger("click");if(cZ&&c0[0].nodeName.toUpperCase()==="A"){this.application.navigateTo(cZ,function(){cY()},cY)}else{cY()}})};cW.query=function(cY){return this.addFutureAction("element "+this.label+" custom query",function(c1,c0,cZ){cY.call(this,c0.elements(),cZ)})};aB.foreach(cV,function(cY){cW[cY]=function(cZ,c1){var c0="element '"+this.label+"' get "+cY+" '"+cZ+"'";if(aB.isDefined(c1)){c0="element '"+this.label+"' set "+cY+" '"+cZ+"' to '"+c1+"'"}return this.addFutureAction(c0,function(c5,c4,c2){var c3=c4.elements();c2(null,c3[cY].call(c3,cZ,c1))})}});aB.foreach(cX,function(cY){cW[cY]=function(c0){var cZ="element '"+this.label+"' "+cY;if(aB.isDefined(c0)){cZ="element '"+this.label+"' set "+cY+" to '"+c0+"'"}return this.addFutureAction(cZ,function(c4,c3,c1){var c2=c3.elements();c1(null,c2[cY].call(c2,c0))})}});return function(cY,cZ){this.dsl.using(cY,cZ);return cW}});aB.scenario.matcher("toEqual",function(cV){return aB.equals(this.actual,cV)});aB.scenario.matcher("toBe",function(cV){return this.actual===cV});aB.scenario.matcher("toBeDefined",function(){return aB.isDefined(this.actual)});aB.scenario.matcher("toBeTruthy",function(){return this.actual});aB.scenario.matcher("toBeFalsy",function(){return !this.actual});aB.scenario.matcher("toMatch",function(cV){return new RegExp(cV).test(this.actual)});aB.scenario.matcher("toBeNull",function(){return this.actual===null});aB.scenario.matcher("toContain",function(cV){return u(this.actual,cV)});aB.scenario.matcher("toBeLessThan",function(cV){return this.actual<cV});aB.scenario.matcher("toBeGreaterThan",function(cV){return this.actual>cV});aB.scenario.output("html",function(cY,c0){var cX=new aB.scenario.ObjectModel(c0);cY.append('<div id="header"> <h1><span class="angular"><angular/></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>');c0.on("InteractiveWait",function(c1,c2){var c3=cX.getSpec(c1.id).getLastStep().ui;c3.find(".test-title").html('waiting for you to <a href="javascript:resume()">resume</a>.')});c0.on("SpecBegin",function(c1){var c2=cZ(c1);c2.find("> .tests").append('<li class="status-pending test-it"></li>');c2=c2.find("> .tests li:last");c2.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>');c2.find("> .test-info .test-name").text(c1.name);c2.find("> .test-info").click(function(){var c4=c2.find("> .scrollpane");var c5=c4.find("> .test-actions");var c3=cY.find("> .test-info .test-name");if(c5.find(":visible").length){c5.hide();c3.removeClass("open").addClass("closed")}else{c5.show();c4.attr("scrollTop",c4.attr("scrollHeight"));c3.removeClass("closed").addClass("open")}});cX.getSpec(c1.id).ui=c2});c0.on("SpecError",function(c1,c2){var c3=cX.getSpec(c1.id).ui;c3.append("<pre></pre>");c3.find("> pre").text(V(c2))});c0.on("SpecEnd",function(c1){c1=cX.getSpec(c1.id);c1.ui.removeClass("status-pending");c1.ui.addClass("status-"+c1.status);c1.ui.find("> .test-info .timer-result").text(c1.duration+"ms");if(c1.status==="success"){c1.ui.find("> .test-info .test-name").addClass("closed");c1.ui.find("> .scrollpane .test-actions").hide()}cW(c1.status)});c0.on("StepBegin",function(c1,c3){c1=cX.getSpec(c1.id);c3=c1.getLastStep();c1.ui.find("> .scrollpane .test-actions").append('<li class="status-pending"></li>');c3.ui=c1.ui.find("> .scrollpane .test-actions li:last");c3.ui.append('<div class="timer-result"></div><div class="test-title"></div>');c3.ui.find("> .test-title").text(c3.name);var c2=c3.ui.parents(".scrollpane");c2.attr("scrollTop",c2.attr("scrollHeight"))});c0.on("StepFailure",function(c1,c3,c2){var c4=cX.getSpec(c1.id).getLastStep().ui;cV(c4,c3.line,c2)});c0.on("StepError",function(c1,c3,c2){var c4=cX.getSpec(c1.id).getLastStep().ui;cV(c4,c3.line,c2)});c0.on("StepEnd",function(c1,c3){c1=cX.getSpec(c1.id);c3=c1.getLastStep();c3.ui.find(".timer-result").text(c3.duration+"ms");c3.ui.removeClass("status-pending");c3.ui.addClass("status-"+c3.status);var c2=c1.ui.find("> .scrollpane");c2.attr("scrollTop",c2.attr("scrollHeight"))});function cZ(c1){var c2=cY.find("#specs");aB.foreach(cX.getDefinitionPath(c1),function(c3){var c4="describe-"+c3.id;if(!cY.find("#"+c4).length){c2.find("> .test-children").append('<div class="test-describe" id="'+c4+'"> <h2></h2> <div class="test-children"></div> <ul class="tests"></ul></div>');cY.find("#"+c4).find("> h2").text("describe: "+c3.name)}c2=cY.find("#"+c4)});return cY.find("#describe-"+c1.definition.id)}function cW(c1){var c2=cY.find("#status-legend .status-"+c1);var c4=c2.text().split(" ");var c3=(c4[0]*1)+1;c2.text(c3+" "+c4[1])}function cV(c3,c1,c2){c3.find(".test-title").append("<pre></pre>");var c4=b8.trim(c1()+"\n\n"+V(c2));c3.find(".test-title pre:last").text(c4)}});aB.scenario.output("json",function(cW,cX){var cV=new aB.scenario.ObjectModel(cX);cX.on("RunnerEnd",function(){cW.text(aB.toJson(cV.value))})});aB.scenario.output("xml",function(cW,cY){var cV=new aB.scenario.ObjectModel(cY);var cZ=function(c0){return new cW.init(c0)};cY.on("RunnerEnd",function(){var c0=cZ("<scenario></scenario>");cW.append(c0);cX(c0,cV.value)});function cX(c2,c0){aB.foreach(c0.children,function(c4){var c3=cZ("<describe></describe>");c3.attr("id",c4.id);c3.attr("name",c4.name);c2.append(c3);cX(c3,c4)});var c1=cZ("<its></its>");c2.append(c1);aB.foreach(c0.specs,function(c3){var c4=cZ("<it></it>");c4.attr("id",c3.id);c4.attr("name",c3.name);c4.attr("duration",c3.duration);c4.attr("status",c3.status);c1.append(c4);aB.foreach(c3.steps,function(c7){var c6=cZ("<step></step>");c6.attr("name",c7.name);c6.attr("duration",c7.duration);c6.attr("status",c7.status);c4.append(c6);if(c7.error){var c5=cZ("<error></error");c6.append(c5);c5.text(V(c6.error))}})})}});aB.scenario.output("object",function(cV,cW){cW.$window.$result=new aB.scenario.ObjectModel(cW).value});var ak=new aB.scenario.Runner(bU);bU.onload=function(){try{if(bi){bi()}}catch(cV){}i(ak,bH(r))}})(window,document,window.onload);document.write('<style type="text/css">@charset "UTF-8";\n\n.ng-format-negative {\n color: red;\n}\n\n.ng-exception {\n border: 2px solid #FF0000;\n font-family: "Courier New", Courier, monospace;\n font-size: smaller;\n white-space: pre;\n}\n\n.ng-validation-error {\n border: 2px solid #FF0000;\n}\n\n\n/*****************\n * TIP\n *****************/\n#ng-callout {\n margin: 0;\n padding: 0;\n border: 0;\n outline: 0;\n font-size: 13px;\n font-weight: normal;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n vertical-align: baseline;\n background: transparent;\n text-decoration: none;\n}\n\n#ng-callout .ng-arrow-left{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n left:-12px;\n height:23px;\n width:10px;\n top:-3px;\n}\n\n#ng-callout .ng-arrow-right{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n height:23px;\n width:11px;\n top:-2px;\n}\n\n#ng-callout {\n position: absolute;\n z-index:100;\n border: 2px solid #CCCCCC;\n background-color: #fff;\n}\n\n#ng-callout .ng-content{\n padding:10px 10px 10px 10px;\n color:#333333;\n}\n\n#ng-callout .ng-title{\n background-color: #CCCCCC;\n text-align: left;\n padding-left: 8px;\n padding-bottom: 5px;\n padding-top: 2px;\n font-weight:bold;\n}\n\n\n/*****************\n * indicators\n *****************/\n.ng-input-indicator-wait {\n background-image: url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAkKAAAALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEvqxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEETAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQJCgAAACwAAAAAEAAQAAAFeCAgAgLZDGU5jgRECEUiCI+yioSDwDJyLKsXoHFQxBSHAoAAFBhqtMJg8DgQBgfrEsJAEAg4YhZIEiwgKtHiMBgtpg3wbUZXGO7kOb1MUKRFMysCChAoggJCIg0GC2aNe4gqQldfL4l/Ag1AXySJgn5LcoE3QXI3IQAh+QQJCgAAACwAAAAAEAAQAAAFdiAgAgLZNGU5joQhCEjxIssqEo8bC9BRjy9Ag7GILQ4QEoE0gBAEBcOpcBA0DoxSK/e8LRIHn+i1cK0IyKdg0VAoljYIg+GgnRrwVS/8IAkICyosBIQpBAMoKy9dImxPhS+GKkFrkX+TigtLlIyKXUF+NjagNiEAIfkECQoAAAAsAAAAABAAEAAABWwgIAICaRhlOY4EIgjH8R7LKhKHGwsMvb4AAy3WODBIBBKCsYA9TjuhDNDKEVSERezQEL0WrhXucRUQGuik7bFlngzqVW9LMl9XWvLdjFaJtDFqZ1cEZUB0dUgvL3dgP4WJZn4jkomWNpSTIyEAIfkECQoAAAAsAAAAABAAEAAABX4gIAICuSxlOY6CIgiD8RrEKgqGOwxwUrMlAoSwIzAGpJpgoSDAGifDY5kopBYDlEpAQBwevxfBtRIUGi8xwWkDNBCIwmC9Vq0aiQQDQuK+VgQPDXV9hCJjBwcFYU5pLwwHXQcMKSmNLQcIAExlbH8JBwttaX0ABAcNbWVbKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICSRBlOY7CIghN8zbEKsKoIjdFzZaEgUBHKChMJtRwcWpAWoWnifm6ESAMhO8lQK0EEAV3rFopIBCEcGwDKAqPh4HUrY4ICHH1dSoTFgcHUiZjBhAJB2AHDykpKAwHAwdzf19KkASIPl9cDgcnDkdtNwiMJCshACH5BAkKAAAALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAkKAAAALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQJCgAAACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");\n background-position: right;\n background-repeat: no-repeat;\n}\n</style>');document.write("<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>"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.